Česky
Kamil Dudka

Tiny programs (C, C++, C#, ...)

File detail

Name:DownloadMainWindow.cs [Download]
Location: tiny > MW5 > proj2 > proj2
Size:14.0 KB
Last modification:2007-08-29 17:43

Source code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace proj2
{
    public partial class MainWindow : Form
    {
        public MainWindow()
        {
            InitializeComponent();
 
            // Catch Exception to avoid dependency problem in component initialization
            try
            {
                this.animatedSplitContainer1.Panel1MinSize = 200;
                this.animatedSplitContainer1.Panel2MinSize = 200;
                this.animatedSplitContainer1.Panel1Collapsed = true;
            }
            catch (InvalidOperationException) { }
 
            // Add "Hide panel" button to "Category panel" toolbar
            this.categoryBrowser1.AddToToolBarDropDown(new ToolStripSeparator());
            ToolStripItem item = new ToolStripMenuItem("&Hide panel");
            item.Click += new EventHandler(hideCategoryBrowser);
            this.categoryBrowser1.AddToToolBarDropDown(item);
        }
 
        /// <summary>
        /// Display info message to status bar.
        /// </summary>
        /// <param name="infoMessage">Message text to display</param>
        private void ShowStatusInfo(string infoMessage)
        {
            statusMessage.BackColor = SystemColors.Info;
            statusMessage.ForeColor = SystemColors.InfoText;
            statusMessage.Text = infoMessage;
 
            statusMessageTimer.Stop();
            statusMessage.Visible = true;
            statusMessageTimer.Start();
        }
 
        /// <summary>
        /// Display error message to status bar.
        /// </summary>
        /// <param name="errorMessage">Mesage text to display</param>
        private void ShowStatusError(string errorMessage)
        {
            statusMessage.BackColor = SystemColors.Control;
            statusMessage.ForeColor = Color.Red;
            statusMessage.Text = errorMessage;
 
            statusMessageTimer.Stop();
            statusMessage.Visible = true;
        }
 
        /// <summary>
        /// Hide error message from status bar.
        /// </summary>
        private void HideStatusError()
        {
            if (
                    statusMessage.BackColor == SystemColors.Control ||
                    statusMessage.ForeColor == Color.Red)
                statusMessage.Visible = false;
        }
 
        /// <summary>
        /// Enable "File/Save" button in toolbar, if changes were made
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dbDataSet_ChangesMade(object sender, EventArgs e)
        {
            fileSavetoolStripButton.Enabled = true;
        }
 
        /// <summary>
        /// Return true, if changes were made
        /// </summary>
        private bool NeedSave
        {
            get { return dbDataSet.HasChanges(); }
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dbDataSet.products' table. You can move, or remove it, as needed.
            this.productsTableAdapter.Fill(this.dbDataSet.products);
            // TODO: This line of code loads data into the 'dbDataSet.productCategories' table. You can move, or remove it, as needed.
            this.productCategoriesTableAdapter.Fill(this.dbDataSet.productCategories);
 
            // CategoryBrowser data binding
            categoryBrowser1.DataSource = dbDataSet;
            categoryBrowser1.ChangesMade += new EventHandler(dbDataSet_ChangesMade);
 
 
            // Initialize "Category" ComboBox in "products" DataGridView
            categoryDataGridViewTextBoxColumn.DataSource = dbDataSet;
            categoryDataGridViewTextBoxColumn.DisplayMember = "productCategories.summary";
            categoryDataGridViewTextBoxColumn.ValueMember = "productCategories.id";
 
            // No changes made till now
            fileSavetoolStripButton.Enabled = false;
        }
 
        /// <summary>
        /// Toggle "Category panel" visibility on coresponding menu item hit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void productcategoriesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            this.animatedSplitContainer1.Panel1Collapsed = item.Checked;
        }
 
        /// <summary>
        /// Hide "Category panel" on Splitter double-click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void animatedSplitContainer1_DoubleClick(object sender, EventArgs e)
        {
            animatedSplitContainer1.Panel1Collapsed = !animatedSplitContainer1.Panel1Collapsed;
        }
 
        /// <summary>
        /// Handle "Category panel" show/hide event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void animatedSplitContainer1_Panel1CollapseChanged(object sender, EventArgs e)
        {
            if (!dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit))
                dataGridView1.CancelEdit();
            if (animatedSplitContainer1.Panel1Collapsed)
            {
                // Hidden
                toolStripButton1.Checked = false;
                productcategoriesToolStripMenuItem.Checked = false;
                dataGridView1.DataMember = "products";
                categoryDataGridViewTextBoxColumn.Visible = true;
                ShowStatusInfo("All products...");
            }
            else
            {
                // Visible
                toolStripButton1.Checked = true;
                productcategoriesToolStripMenuItem.Checked = true;
                dataGridView1.DataMember = "productCategories.FK_product_category";
                categoryDataGridViewTextBoxColumn.Visible = false;
                ShowStatusInfo("Select category to view products...");
            }
        }
 
        /// <summary>
        /// Handle SplitContainer.Animated value change event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void animatedSplitContainer1_AnimatedChanged(object sender, EventArgs e)
        {
            bool bAnimated = animatedSplitContainer1.Animated;
            animationsToolStripMenuItem.Checked = bAnimated;
            ShowStatusInfo((bAnimated) ?
                "Animations turned on..." :
                "Animations turned off...");
        }
 
        /// <summary>
        /// Toggle SplitContainer animation on corresponding menu item hit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void animationsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            animatedSplitContainer1.Animated = !animationsToolStripMenuItem.Checked;
        }
 
        /// <summary>
        /// Menu-item File/Exit hit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
 
        /// <summary>
        /// Toggle "Category panel" visibility on coresponding toolbar button hit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void categoryToolStripButton_Click(object sender, EventArgs e)
        {
            animatedSplitContainer1.Panel1Collapsed = toolStripButton1.Checked;
        }
 
        /// <summary>
        /// Menu item File/Save hit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fileSaveMenuItem_Click(object sender, EventArgs e)
        {
            if (!dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit))
                dataGridView1.CancelEdit();
 
            this.SuspendLayout();
            try
            {
                productCategoriesTableAdapter.Update(dbDataSet);
                productsTableAdapter.Update(dbDataSet);
                ShowStatusInfo("Changes saved...");
                fileSavetoolStripButton.Enabled = false;
            }
            catch (System.Data.DBConcurrencyException ex) {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                this.SuspendLayout();
                dbDataSet.Clear();
                Form1_Load(this, EventArgs.Empty);
                this.ResumeLayout();
                ShowStatusInfo("Changes saved...");
            }
            catch (System.Data.SqlClient.SqlException)
            {
                ShowStatusError("Error during save operation. Try later.");
            }
            this.ResumeLayout();
        }
 
        /// <summary>
        /// Check "File" menu items usability when dropping down
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fileToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
        {
            fileSaveMenuItem.Enabled = NeedSave;
            fileDiscardMenuItem.Enabled = NeedSave;
        }
 
        /// <summary>
        /// Menu item File/Discard hit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fileDiscardMenuItem_Click(object sender, EventArgs e)
        {
            // Ask User
            if (DialogResult.Cancel == MessageBox.Show(
                    "Are you sure to discard all changes?",
                    this.Text,
                    MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Exclamation))
                return;
 
            // Reload data from db
            this.SuspendLayout();
            dbDataSet.Clear();
            Form1_Load(this, EventArgs.Empty);
            ShowStatusInfo("Changes discarded...");
            this.ResumeLayout();
        }
 
        /// <summary>
        /// Hide status messsage after specified interval
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void statusMessageTimer_Tick(object sender, EventArgs e)
        {
            statusMessage.Visible = false;
        }
 
        /// <summary>
        /// Delegate status info messages from CategoryBrowser component
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void categoryBrowser1_StatusMessageChanged(object sender, proj2.UserControls.CategoryBrowser.StatusMessageEventArgs e)
        {
            ShowStatusInfo(e.StatusMessageText);
        }
 
        /// <summary>
        /// Category browser add-on item "Hide panel" callback
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hideCategoryBrowser(object sender, EventArgs e)
        {
            animatedSplitContainer1.Panel1Collapsed = true;
        }
 
        /// <summary>
        /// Ask user for data saving on application exit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = false;
            if (!NeedSave)
                return;
 
            // Ask user
            DialogResult res = MessageBox.Show(
                "Save changes to database?",
                this.Text,
                MessageBoxButtons.YesNoCancel,
                MessageBoxIcon.Question);
            switch (res)
            {
                case DialogResult.Yes:
                    fileSaveMenuItem_Click(this, EventArgs.Empty);
                    if (!NeedSave)
                        break;
 
                    // 2 redundant lines for stupid C# compilator
                    else
                        goto case DialogResult.Cancel;
                case DialogResult.Cancel:
                    e.Cancel = true;
                    break;
            }
        }
 
        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            DataGridView view = (DataGridView)sender;
            if (e.ColumnIndex < 0)
                return;
            string errorString =
                "Invalid value of \"" + view.Columns[e.ColumnIndex].HeaderText +"\". " +
                "Press [Esc] to cancel.";
            view.Rows[e.RowIndex].ErrorText = errorString;
            ShowStatusError(errorString);
        }
 
        private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;
            DataGridViewRow row =
                grid.Rows[e.RowIndex];
            if (row.ErrorText.Length != 0)
            {
                row.ErrorText = "";
                HideStatusError();
            }
        }
 
        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;
            DataGridViewRow row =
                grid.Rows[e.RowIndex];
            if (row.ErrorText.Length != 0)
            {
                row.ErrorText = "";
                HideStatusError();
            }
 
            dbDataSet_ChangesMade(sender, EventArgs.Empty);
 
            if (e.ColumnIndex != grid.Columns["modifiedDataGridViewTextBoxColumn"].Index)
                row.Cells["modifiedDataGridViewTextBoxColumn"].Value = DateTime.Now;
 
        }
 
        private void dataGridView1_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            dbDataSet_ChangesMade(sender, EventArgs.Empty);
        }
    }
}