How to create MDI in Windows form C#

Creating MDI Parent FormsThe base of a Multiple Document Interface (MDI) is the MDI parent form. This is the form that holds the MDI child windows, which are all the "sub-windows" in which the client work together with the MDI application.
To Create MDI Parent Forms:
Create a new form and add the code.

this.IsMDIContainer = true;
This assign the form as an MDI container for child windows.
Creating MDI Child FormsAn vital constituent of Multiple Document Interface (MDI) Applications is the MDI child forms, as these are the main windows for client interaction.
To Create MDI Child Forms:
Form frmchild=new Form();
frmchild.MDIParent=
this
;
frmchild.Show();
Determining the Active MDI Child:
In a number of circumstance, we desire to give a command that operates on the control with the focus on the at present active child form.

For the reason that an application can have many instances of the same child form, the process wants to be acquainted with which form to use. To specify this, use the ActiveForm property of an MDI Form, which returns the child form that has the focus.

In any case one MDI child form must be loaded and visible when you access the ActiveForm property, or an error is returned.
Arranging Child Forms:
Frequently, applications will have menu commands for actions such as Tile, Cascade, and Arrange, with concerning to the open MDI child forms. One can use the LayoutMDI method with the MDILayout enumeration to rearrange the child forms in an MDI parent form.
The MDILayout enumeration can be set to four different values, which will display child forms as cascading, as horizontally or vertically. Often, these methods are used as the event handlers called by a menu item's Click event. In this way, a menu item with the text "Cascade Windows" can have the desired effect on the MDI child windows.
In the example below, the event handler for the Click event for the Cascade menu item sets the MDILayout enumeration to Cascade for the child windows of the MDI Parent form.

Example:using System;using System.ComponentModel;using System.WinForms;using System.Drawing;public class MDI :Form
{
private MainMenu mainMenu;private int Count=0;public MDI()
{
this.IsMDIContainer=true;this.Text="MDI Demo";
mainMenu = 
new MainMenu();
MenuItem File = mainMenu.MenuItems.Add("&File");
File.MenuItems.Add(
new MenuItem("&New",new EventHandlerthis.FileNew_clicked),Shortcut.CtrlN));
File.MenuItems.Add(
new MenuItem("&Active Child",new EventHandlerthis.FindActive_clicked),Shortcut.CtrlA));
File.MenuItems.Add(
new MenuItem("-"));
File.MenuItems.Add(
new MenuItem("&Exit",new EventHandlerthis.FileExit_clicked),Shortcut.CtrlX));
MenuItem Arrange = mainMenu.MenuItems.Add("&Arrange");
Arrange.MenuItems.Add(
new MenuItem("&Cascade",new EventHandlerthis.Cascade_clicked),Shortcut.F1));
Arrange.MenuItems.Add(
new MenuItem("&Horizontal",new EventHandlerthis.Horizontal_clicked),Shortcut.F2));
Arrange.MenuItems.Add(
new MenuItem("&Vertical",new EventHandlerthis.Vertical_clicked),Shortcut.F3));this.Menu=mainMenu;
mainMenu.GetForm().BackColor = Color.Indigo ;
}
private void FileExit_clicked(object sender, EventArgs e)
{
this.Close();
}
private void FindActive_clicked(object sender, EventArgs e)
{
MessageBox.Show(
this.ActiveMDIChild.Text,"MDI FORM",MessageBox.IconInformation);
}
private void FileNew_clicked(object sender, EventArgs e)
{
Form frmchild=
new Form();
frmchild.MDIParent=
this;
frmchild.Show();
frmchild.Text="Child Form" + Count.ToString();
Count++;
}
private void pop_Clicked(object sender, EventArgs e)
{
MessageBox.Show("Popupmenu","MENU_CREATION",MessageBox.IconInformation);
}
private void Cascade_clicked(object sender, EventArgs e)
{this.LayoutMDI(MDILayout.Cascade );
}
private void Horizontal_clicked(object sender, EventArgs e)
{
this.LayoutMDI(MDILayout.TileHorizontal);
}
private void Vertical_clicked(object sender, EventArgs e)
{
this.LayoutMDI(MDILayout.TileVertical);
}
public static void Main(string[] args)
{
Application.Run(
new MDI());
}
}

Output:

MDICascadeGAG2.jpgMdiAppGAG1.jpg

How to create Auto ID using C# windows form with Acess Database

Let’s start with create a new windows form. 
We need one Label, one TextBox one button and one GridView.



The code is shown below:
using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Windows.Forms;  
using System.Data.OleDb;  
namespace idgenerator  
{  
    public partial class Form1 : Form  
    {  
        OleDbConnection connectiondb = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\C# Cor\database\mydatabase.accdb;Persist Security Info=False");  
        OleDbCommand com;  
        string str;  
        public Form1()  
        {  
            InitializeComponent();  
            new_id();  
            showdata();  
        }  
        private void Form1_Load(object sender, EventArgs e)  
        {  
        }  
        private void new_id()  
        {  
            if (connectiondb.State == ConnectionState.Closed)  
            {  
                connectiondb.Open();  
            }  
            str = "select max(admin_create_id) from tbl_user";  
            com = new OleDbCommand(str, connectiondb);  
            com.CommandType = CommandType.Text;  
            Int32 max = (Int32)com.ExecuteScalar();  
            label3.Text = (max + 1).ToString();  
            connectiondb.Close();  
        }  
        private void button1_Click(object sender, EventArgs e)  
        {  
            if (connectiondb.State == ConnectionState.Closed)  
            {  
                connectiondb.Open();  
            }  
            str = "insert into tbl_user (admin_create_id,sName) values (@admin_create_id,@sName)";  
            com = new OleDbCommand(str, connectiondb);  
            com.Parameters.AddWithValue("@admin_create_id", label3.Text);  
            com.Parameters.AddWithValue("@sName", textBox2.Text);  
            com.ExecuteNonQuery();  
            connectiondb.Close();  
            MessageBox.Show("Records Successfuly Inserted");  
            showdata();  
            new_id();  
        }  
        private void showdata()  
        {  
            if (connectiondb.State == ConnectionState.Closed)  
            {  
                connectiondb.Open();  
            }  
            string strSql = "Select admin_create_id,sName from tbl_user";  
            OleDbCommand cmd = new OleDbCommand(strSql, connectiondb);  
            cmd.CommandType = CommandType.Text;  
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);  
            DataTable dt = new DataTable();  
            da.Fill(dt);  
            dataGridView1.DataSource = dt;  
            connectiondb.Close();  
        }  
    }  
}  
Result




How to Make Sticky Notes Application using C#


Make Sticky Notes Windows frrrm Application



Steps:

1. Add a form in your application and make the form border style none. Set transparency key property as form background color so it will make your form transparent.

For viewing image for step1 see my article how to make screen saver.

2. Add a ContexMenuStrip, Timer control and add other controls as shown in the figure.

sticky.gif

3. Code Behind.

        /*
         *  When you run this application a directory named note and a text file named note.txt will generate in the C:\Program Files 
         */
 
        //this is the exit menu of the contexmenustrip        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {            
            this.Close();
        }
 
        //this is the Font menu of the contexmenustrip        private void fontToolStripMenuItem_Click(object sender, EventArgs e)
        {            
            FontDialog font = new FontDialog();
            if (font.ShowDialog() == DialogResult.OK)
            {
                txt_note.Font = font.Font;                
            }
       }
       //this is the FontColor menu of the contexmenustrip            private void fontColorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ColorDialog color = new ColorDialog();
            if (color.ShowDialog() == DialogResult.OK)
            {
                txt_note.ForeColor = color.Color;
            }
        }
 
        StreamWriter sw;
        StreamReader sr;
        FileStream note;
        private void Form_note_Load(object sender, EventArgs e)
        {     
            lbl_date.Text = System.DateTime.Now.ToLocalTime().ToString("dd/MM/yyyy  hh:mm:ss");
 
           //Time is enable in the form load even            timer1.Start();
            
            createFile();
 
            readNote();
        }
 
        /*         * creaFile() function is called in the Form load event
         * It generate the directory ann file as mention above.
         */
 
        private void createFile()
        {
            bool existDir = Directory.Exists(@"C:\Program Files\Note");
            bool exitFolder = File.Exists(@"C:\Program Files\Note\note.txt");
 
           //If directory and text file is generated then it will not generate again when you run application next time.            if (!(existDir && exitFolder))
            {
                Directory.CreateDirectory(@"C:\Program Files\Note");
                note = File.Create(@"C:\Program Files\Note\note.txt");
                note.Close();
 
                sw = new StreamWriter(@"C:\Program Files\Note\note.txt");
                sw.Write("Have a nice day\nWel-come from Priyank");
                sw.Close();
            }
        }
       /*        * This is the richTextBox which is set into the pictureBox2.
        * Whatever you write in this text box it will saved into the note.txt file.
        */ 
 
        private void txt_writeNote_TextChanged(object sender, EventArgs e)
        {
            sr.Close();
            sw = new StreamWriter(@"C:\Program Files\Note\note.txt");
            sw.Write(txt_writeNote.Text);
            sw.Close();
        }
        
        /*         * After writing your note in the text box when you close second Panel readNote() function come to the action.
         * It reads all the lines from the note.txt and it will display in the txt_note.Text which is set in the pictureBox1
         */
 
        private void readNote()
        {
            double size;
            float size1;
            string text;//,style;            FontStyle style;
 
            sr = new StreamReader(@"C:\Program Files\Note\note.txt");
            text = sr.ReadToEnd();
            txt_note.Text = text;
            txt_writeNote.Text = text;
            sr.Close();            
        }
 
        /*         * when you click here panel2 will visible so you are able to write your note.
         */
 
        private void btn_add_Click(object sender, EventArgs e)
        {
            panel2.Visible = true;
        }
        /*         * After click on close button you are able to see your note.
         */
 
        private void btn_close_Click(object sender, EventArgs e)
        {
            panel2.Visible = false;
            readNote();
        }       
        //Set the interval of the timer 1000.        private void timer1_Tick(object sender, EventArgs e)
        {
            //display the current time and date            lbl_date.Text =System.DateTime.Now.ToLocalTime().ToString("dd/MM/yyyy  hh:mm:ss");
       }

How to use Status Strip Control in C#

Making a StatusStrip Control

A typical status bar control, placed on the bottom of a Form is used to display some text that represents the status of the application and user actions. In the previous versions of the Windows Forms, the StatusBar control is used to provide the status bar functionality. In Windows Forms 4.0 that is a part of Visual Studio 2010, the StatusStrip control replaces the StatusBar control. The StatusStrip control not only provides status bar functionality but also provides features to add rich user interfaces to a status bar such as a ProgressBar, DropDownButton and SplitButton controls.
In this article, we will learn how to build status bar enabled Windows applications using Visual Studio 2010.
Similar to any other Windows Forms control, we can use either use design-time approach or runtime approach to create a StatusStrip control. The design-time approach is used in the most of the cases but there will be times when we may need the run-time approach.  
Note: In this tutorial, I use the design-time approach as the default approach but I will also show the run-time approach side by side.
Creating a StatusStrip
To build a StatusStrip control at design-time, simply drag and drop a StatusStrip control from the Toolbox to the Form. The default StatusStrip control is docked at the bottom of the Form as shown in Figure 1.
StatusStrip1.gif
Figure 1
The designer also allows you to add several controls to a StatusStrip control including a StatusLabel, ProgressBar, DropDownButton, and a SplitButton. If you click on little dropdown icon, you will see four of these controls in the listing as shown in Figure 2. As soon as you select one of these controls, it will be added to the StatusStrip control.
StatusStrip2.gif
Figure 2
Run-time
In Windows Forms, the StatusStrip class represents the StatusStrip control. Similar to any other Windows control, we create a class object, set its properties, methods and events and add the control to the Form's controls.
The code snippet in Listing 1 creates a StatusStrip control. Once a control is created, we need to set its properties and call Form.Controls.Add method to add the StatusStrip control to a Form's controls.
StatusStrip dynamicStatusStrip = new System.Windows.Forms.StatusStrip();
// Set StatusStrip properties, methods, and events
// Add StatusStrip child controls

Controls.Add(dynamicStatusStrip);
Listing 1
StatusStrip Properties
The StatusStrip class is inherited from the ToolStrip ->ScrollableControl->Control classes and hence has all of the common properties supported by a Windows Forms control. Some of these common properties include Font, BackColor, Dock, BackgroundImage, and TextDirection.
We can set the StatusStrip control properties using the Properties Window that looks like Figure 3.
StatusStrip3.gif
Figure 3
Run-time
The code snippet in Listing 2 sets the Name, Text, BackColor, Font, and ForeColor properties of the the StatusStrip control at run-time.
StatusStrip dynamicStatusStrip = new System.Windows.Forms.StatusStrip();           
dynamicStatusStrip.Name = "DynamicStatusStrip";
dynamicStatusStrip.Text = "statusStrip1";
dynamicStatusStrip.BackColor = Color.OrangeRed;
dynamicStatusStrip.Font = new Font("Georgia", 14, FontStyle.Italic);
dynamicStatusStrip.ForeColor = Color.White; 
Listing 2
Docking a StatusStrip
Unlike the old StatusBar control, now we can dock a StatusStrip control on a Form. The Dock property of the StatusStrip is used to set docking. A StatusStrip control can be docked at top, bottom, left, right, or center.
Figure 4 shows a top docked StatusStrip control.
StatusStrip4.gif
Figure 4
Run-time
The Dock property is a type of DockStyle enumeration. The code snippet in Listing 3 sets the Dock property at run-time.
dynamicStatusStrip.Dock = DockStyle.Top;
Listing 3
Background Image
The BackColor property sets the background color of a StatusStrip control. We can also set an image as the background color of a StatusStrip control. The BackgroundImage property is used to set the background image of a StatusStrip control. When you click on the BackgroundImage property in the Property designer, you will see the Resource Editor that looks like Figure 5, where you can browse an image or use local resources using the Import button.

StatusStrip5.gif
Figure 5
We can also set the layout of the background image using the BackgroundImageLayout property that can be stretched, tiled, centered, centered or zoomed as you can see in Figure 6.
 StatusStrip6.gif

Figure 6
Run-time
The BackgroundImage property takes an Image type. We can use an ImageList to manage all the images. An ImageList is an object of Image objects.  The code snippet in Listing 4 creates an ImageList object and adds an image to it from a file. The code then sets the BackgroundImage and BackgroundImageLayout properties.
ImageList dynamicImgList = newImageList();dynamicImgList.Images.Add(Image.FromFile(@"C:\Images\Neel\18.jpg"));
dynamicStatusStrip.BackgroundImage = dynamicImgList.Images[0];
dynamicStatusStrip.BackgroundImageLayout = ImageLayout.Center;
Listing 4
Text Direction
The TextDirection is another useful property that was missing in the StatusBar control. Using the TextDirection property, we can set the text direction of the StatusStrip control. It has three properties – Horizontal, Vertical90 and Vertical270. Figure 7 shows Verical90 text of a StatusStrip control.
StatusStrip7.gif
Figure 7
Run-time
The TextDirection property is a type of ToolStripTextDirection enumeration. The code snippet in Listing 5 sets the Dock property at run-time.
dynamicStatusStrip.TextDirection = ToolStripTextDirection.Vertical270;
Listing 5
Sizing Grip, Grip Style, and Layout Style
The sizing grip is a little sizing handle in the lower right corner of a control. Using the SizingGrip property is used to enable the sizing handle. The SizingGrip property works with the GripStyle and the LayoutStyle properties. The GripStyle property is used to show or hide the grip style. The LayoutStyle property as shown in Figure 8 represents the layout type of the grip.
StatusStrip8.gif
Figure 8
Note: The sizing grip will not be displayed unless you also set the LayoutStyle property to one of the overflow values.
Run-time
The code snippet in Listing 6 sets the SizingGrip, the GripStyle, and the LayoutStyle properties at run-time.
dynamicStatusStrip.SizingGrip = true;
dynamicStatusStrip.GripStyle = ToolStripGripStyle.Visible;
dynamicStatusStrip.LayoutStyle = ToolStripLayoutStyle.HorizontalStackWithOverflow; 
Listing 6
Adding StatusStrip Items
A StatusStrip control is nothing but a container for the child controls. A StatusStrip control can host several child controls. These child controls are represented by the Items property. If you click on the Items property of the StatusStrip control, you will see Items Collection Editor where you can add, update, and delete the child controls. If you click on the Items property, you will see the Item Collection Editor where you can select an item type from the DropDown and click Add button to add the child control. The DropDown has four item types and these items are the ToolStripStatusLabel,  ToolStripProgressBar, ToolStripDropDownButton, and ToolStripSplitButton.
Now, let's add one item of each control type as you can see from Figure 9. Once you add an item, you will see all the properties in the right side properties window.
StatusStrip9.gif
Figure 9
Here comes the good part. All of the child controls placed on a StatusStrip control have their own unique IDs and can be used as independent controls. That means, you can use and control these child controls similar to any other control on a Form.
After adding child controls and setting their properties, the final StatusStrip control looks like Figure 10.
StatusStrip10.gif
Figure 10
We can also set the properties, events and methods of a child control by right click on the child control on the StatusStrip control and click on the Properties window like any other control. If you right click and select Properties of the ProgressBar child control, you will see something like Figure 11.
StatusStrip11.gif
Figure 11
StatusBar Enabled Application
Alright! Let's build a StatusBar enabled application.
I create a Windows Forms application and add a StatusStrip control to the Form. I also add three Button controls to the Form. After that, I add two StatusStripStatusLabel, one StatusStripDropDownButton, and one StatusStripProgressBar child controls to the Form.
Now I add three menu items to the StatusStripDropDownButton by using its Items property and change its text and foreground colors to Red, Green, and Blue. I also add the Click event handlers for these menu items. The event handler of menu items looks like following:
private void RedMenuItemClick(object sender, EventArgs e)
{
} 
The final Form with the StatusStrip control and its items looks like Figure 12. 
StatusStrip12.gif
Figure 12
On the Start button click event handler, I set the Value and the Text properties of the ProgressBar as listed in Listing 7.
private void StartButton_Click(object sender, EventArgs e)
{
    toolStripProgressBar1.Value = 90;
    ProgressLabel.Text = toolStripProgressBar1.Value.ToString();
}
Listing 7
One last thing I need to do is, set the background color of the StatusStrip control to Red, Green, and Blue on the Red, Green, and Blue menu item click event handlers.
private void RedMenuItemClick(object sender, EventArgs e)
{
    statusStrip1.BackColor = Color.Red;
private void GreenMenuItemClick(object sender, EventArgs e)
{
    statusStrip1.BackColor = Color.Green;
private void BlueMenuItemClick(object sender, EventArgs e)
{
    statusStrip1.BackColor = Color.Blue;
}