Close
Login to Your Account
Faadooengineers




Results 1 to 1 of 1

Thread: Windows Form Standard Controls

  1. #1

    Txt 32 Windows Form Standard Controls

    Standard control in c#
    Button
    A button control accepts clicks. In Windows Forms we use a Button control that accepts click events and performs other actions in the user interface. This control provides a way to accept input—and invoke logic based on that input. You can use a Button control to perform an action when the user clicks or presses a key to activate the button.
    using System;
    using System.Windows.Forms;

    namespace WindowsFormsApplication21
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
    MessageBox.Show("Dot Net Perls says hello.", "How is your day going?");
    }
    }
    }

    List Box

    A ListBox control provides an interface to display a list of items. Users can select one or more items from the list. A ListBox may be used to display multiple columns and these columns may have images and other controls.

    In this tutorial, we will learn how to create a ListBox control at design-time as well as at run-time. We will also see how to create a multiple-column ListBox control with single and multiple selections. This article also covers most of the properties and methods of the ListBox control.

    Creating a ListBox
    There are two approaches to create a ListBox control in Windows Forms. Either we can use the Forms designer to create a control at design-time or we can use the ListBox class to create a control at run-time.

    Design-time
    In our first approach, we are going to create a ListBox control at design-time using the Forms designer.
    To create a ListBox control at design-time, we simply drag a ListBox control from the Toolbox and drop it to a Form in Visual Studio. After you drag and drop a ListBox onto a Form, the ListBox looks as in Figure 1. Once a ListBox is on the Form, you can move it around and resize it using the mouse and set its properties and events.




    Setting ListBox Properties

    Name
    The Name property represents a unique name of a ListBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a ListBox control:
    listBox1.Name = "ListBox1";

    Location, Height, Width and Size
    The Location property takes a Point that specifies the starting position of the ListBox on a Form. You may also use the Left and Top properties to specify the location of a control from the top-left corner of the Form. The Size property specifies the size of the control. We can also use the Width and Height properties instead of the Size property. The following code snippet sets the Location, Width, and Height properties of a ListBox control:
    listBox1.Location = new System.Drawing.Point(12, 12);
    listBox1.Size = new System.Drawing.Size(245, 200);

    Font
    The Font property represents the font of the text of a ListBox control. If you click on the Font property in Properties window, you will see the Font name, size and other font options. The following code snippet sets the Font property at run-time:
    listBox1.Font = new Font("Georgia", 16);

    Background and Foreground
    The BackColor and ForeColor properties are used to set the background and foreground colors of a ListBox respectively. If you click on these properties in the Properties window, then the Color Dialog pops up.
    Alternatively, you can set background and foreground colors at run-time. The following code snippet sets the BackColor and ForeColor properties:
    listBox1.BackColor = System.Drawing.Color.Orange;
    listBox1.ForeColor = System.Drawing.Color.Black;

    The new ListBox with background and foreground looks as in Figure 3.




    You can also set the borders style of a ListBox by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values: FixedSingle, Fixed3D, and None. The default value of the border style is Fixed3D. The following code snippet sets the border style of a ListBox to FixedSingle:

    listBox1.BorderStyle = BorderStyle.FixedSingle;

    ListBox Items
    The Items property is used to add and work with items in a ListBox. We can add items to a ListBox at design-time from the Properties Window by clicking on the Items Collection
    When you click on the Collections, the String Collection Editor window will pop up where you can type strings. Each line added to this collection will become a ListBox item. as you can see from Figure




    You can add the same items at run-time by using the following code snippet:
    listBox1.Items.Add("Mahesh Chand");
    listBox1.Items.Add("Mike Gold");
    listBox1.Items.Add("Praveen Kumar");
    listBox1.Items.Add("Raj Beniwal");

    Getting All Items
    To get all items, we use the Items property and loop through it to read all the items. The following code snippet loops through all items and adds item contents to a StringBuilder and displays it in a MessageBox:
    private void GetItemsButton_Click(object sender, EventArgs e)
    {
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    foreach (object item in listBox1.Items)
    {
    sb.Append(item.ToString());
    sb.Append(" ");
    }
    MessageBox.Show(sb.ToString());
    }

    Selected Text and Item
    The Text property is used to set and get text of a ListBox. The following code snippet sets and gets the current text of a ListBox:
    MessageBox.Show(listBox1.Text);

    We can also get text associated with the currently selected item using the Items property:
    string selectedItem = listBox1.Items
    [listBox1.SelectedIndex].ToString();

    To select an item in a ListBox, we can use the SetSelect method that takes an item index and a true or false value where the true value represents the item to be selected.
    The following code snippet sets a ListBox to allow multiple selection and selects the second and third items in the list:


    listBox1.SelectionMode = SelectionMode.MultiSimple;
    listBox1.SetSelected(1, true);
    listBox1.SetSelected(2, true);

    We can clear all selected items by calling the ClearSelected method, as in:
    listBox1.ClearSelected();

    Combo Box
    We can create a ComboBox control using a Forms designer at design-time or using the ComboBox class in code at run-time.
    To create a ComboBox control at design-time, you simply drag and drop a ComboBox control from Toolbox to a Form in Visual Studio. After you drag and drop a ComboBox on a Form, the ComboBox looks like Figure. Once a ComboBox is on the Form, you can move it around and resize it using mouse and set its properties and events.



    Setting ComboBox Properties
    After you place a ComboBox control on a Form, the next step is to set properties.
    The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure.

    Name
    Name property represents a unique name of a ComboBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a ComboBox control.
    comboBox1.Name = "comboBox1";

    Location, Height, Width and Size
    The Location property takes a Point that specifies the starting position of the ComboBox on a Form. You may also use Left and Top properties to specify the location of a control from the left top corner of the Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a ComboBox control.
    comboBox1.Location = New System.Drawing.Point(12, 12);
    comboBox1.Size = New System.Drawing.Size(300, 25);
    comboBox1.Width = 300;
    comboBox1.Height = 25;

    DropDownHeight and DropDownWidth
    You can control the size of the dropdown area of a ComboBox. The DropDownHeight and DropDownWidth properties represent the height and width of the dropdown area in pixel respectively. If the DropDownWidth and DropDownHeight properties are less than the Width and Height values, they will not be applicable. If all the items do not fit in the size of the dropdown area, the scrollbars will appear as you can see from Figure.

    The following code snippet sets the height and width of the dropdown area of a ComboBox.

    comboBox1.DropDownHeight = 50;
    comboBox1.DropDownWidth = 300;

    Font
    Font property represents the font of text of a ComboBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options.
    comboBox1.Font = new Font("Georgia", 16);

    Background and Foreground
    BackColor and ForeColor properties are used to set background and foreground color of a ComboBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.
    Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.
    comboBox1.BackColor = System.Drawing.Color.Orange;
    comboBox1.ForeColor = System.Drawing.Color.Black;

    The new ComboBox with background and foreground looks like Figure.







    ComboBox Items
    The Items property is used to add and work with items in a ComboBox. We can add items to a ComboBox at design-time from Properties Window by clicking on Items Collection as you can see in Figure 5.
    When you click on the Collections, the String Collection Editor window will pop up where you can type strings. Each line added to this collection will become a ComboBox item. I add four items as you can see from Figure.


    Figure
    Selected Text and Item
    Text property is used to set and get text of a ComboBox. The following code snippet sets and gets current text of a ComboBox.
    comboBox1.Text = "Mahesh Chand";
    MessageBox.Show(comboBox1.Text);

    We can also get text associated with currently selected item by using Items property.
    string selectedItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();

    DropDownStyle
    DropDownStyle property is used to gets and sets the style of a ComboBox. It is a type of ComboBoxStyle enumeration.
    The ComboBoxStyle enumeration has following three values.
    • Simple - List is always visible and the text portion is editable.
    • DropDown €“ List is displayed by clicking the down arrow and that the text portion is editable.
    • DropDownList - List is displayed by clicking the down arrow and that the text portion is not editable.

    The following code snippet sets the DropDownStyle property of a ComboBox to DropDownList.
    comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;


    Checkbox

    We can create a CheckBox control using a Forms designer at design-time or using the CheckBox class in code at run-time (also known as dynamically).
    To create a CheckBox control at design-time, you simply drag and drop a CheckBox control from Toolbox to a Form in Visual Studio. After you drag and drop a CheckBox on a Form, the CheckBox looks like in Figure. Once a CheckBox is on the Form, you can move it around and resize it using mouse and set its properties and events.



    Setting CheckBox Properties

    After you place a CheckBox control on a Form, the next step is to set properties.
    The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item.

    Location, Height, Width, and Size

    The Location property takes a Point that specifies the starting position of the CheckBox on a Form. You may also use Left and Top properties to specify the location of a control from the left top corner of the Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a CheckBox control.
    // Set CheckBox properties
    dynamicCheckBox.Location = new Point(20, 150);
    dynamicCheckBox.Height = 40;
    dynamicCheckBox.Width = 300;

    Background, Foreground, BorderStyle

    BackColor and ForeColor properties are used to set background and foreground color of a CheckBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.
    Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.
    // Set background and foreground
    dynamicCheckBox.BackColor = Color.Red;
    dynamicCheckBox.ForeColor = Color.Blue;

    Name
    Name property represents a unique name of a CheckBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a CheckBox control.
    dynamicCheckBox.Name = "DynamicCheckBox";
    string name = dynamicCheckBox.Name;
    Text and TextAlign
    Text property of a CheckBox represents the current text of a CheckBox control. The TextAlign property represents text alignment that can be Left, Center, or Right. The following code snippet sets the Text and TextAlign properties and gets the size of a CheckBox control.
    dynamicCheckBox.Text = "I am a Dynamic CheckBox";
    dynamicCheckBox.TextAlign = ContentAlignment.MiddleCenter;

    Font
    Font property represents the font of text of a CheckBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.
    dynamicCheckBox.Font = new Font("Georgia", 16);

    Appearance
    Appearance property of CheckBox can be used to set the appearance of a CheckBox to a Button or a CheckBox. The following property makes a CheckBox look like a Button control.
    dynamicCheckBox.Appearance = Appearance.Button;

    Image in CheckBox

    The Image property of a CheckBox control is used to set the background as an image. The Image property needs an Image object. The Image class has a static method called FromFile that takes an image file name with full path and creates an Image object.
    You can also align image and text. The ImageAlign and TextAlign properties of CheckBox are used for this purpose.
    The following code snippet sets an image as a CheckBox background.

    // Assign an image to the CheckBox.
    dynamicCheckBox.Image = Image.FromFile(@"C:\Images\Dock.jpg");
    // Align the image and text on the CheckBox.
    dynamicCheckBox.ImageAlign = ContentAlignment.MiddleRight;
    // Give the CheckBox a flat appearance.
    dynamicCheckBox.FlatStyle = FlatStyle.Flat;

    CheckBox States
    A typical CheckBox control has two possible states €“ Checked and Unchecked. Checked state is when the CheckBox has check mark on and Unchecked is when the CheckBox is not checked. Typically, we use a mouse to check or uncheck a CheckBox.
    Checked property is true when a CheckBox is in checked state.
    dynamicCheckBox.Checked = true;

    CheckState property represents the state of a CheckBox. It can be checked or unchecked. Usually, we check if a CheckBox is checked or not and decide to take an action on that state something like following code snippet.
    if (dynamicCheckBox.Checked)
    {
    // Do something when CheckBox is checked
    }
    else
    {
    // Do something here when CheckBox is not checked
    }

    ThreeState is a new property added to the CheckBox in latest versions of Windows Forms. When thisproperty is true, the CheckBox has three states - Checked, Unchecked, and Indeterminate. The following code snippet sets and checks CheckState.
    dynamicCheckBox.CheckState = CheckState.Indeterminate;

    if (dynamicCheckBox.CheckState == CheckState.Checked)
    {
    }
    else if (dynamicCheckBox.CheckState == CheckState.Indeterminate)
    {
    }
    else
    {
    }

    AutoCheck property represents whether the Checked or CheckState values and the CheckBox's appearance are automatically changed when the CheckBox is clicked. By default this property is true but if set to false.
    dynamicCheckBox.AutoCheck = false;

    Radio Button
    A RadioButton control provides a round interface to select one option from a number of options. Radio buttons are usually placed in a group on a container control such as a Panel or a GroupBox and one of them is selected.

    Creating a RadioButton
    We can create a RadioButton control using a Forms designer at design-time or using the RadioButton class in code at run-time (also known as dynamically).
    To create a RadioButton control at design-time, you simply drag and drop a RadioButton control from Toolbox to a Form in Visual Studio. After you drag and drop a RadioButton on a Form, the RadioButton looks like Figure. Once a RadioButton is on the Form, you can move it around and resize it using mouse and set its properties and events.



    Setting RadioButton Properties

    After you place a RadioButton control on a Form, the next step is to set properties.
    The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure .

    Location, Height, Width, and Size

    The Location property takes a Point that specifies the starting position of the RadioButton on a Form. You may also use Left and Top properties to specify the location of a control from the left top corner of the Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a RadioButton control.
    dynamicRadioButton.Location = new Point(20, 150);
    dynamicRadioButton.Height = 40;
    dynamicRadioButton.Width = 300;

    Background, Foreground, BorderStyle
    BackColor and ForeColor properties are used to set background and foreground color of a RadioButton respectively. If you click on these properties in Properties window, the Color Dialog pops up.
    Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.
    dynamicRadioButton.BackColor = Color.Red;
    dynamicRadioButton.ForeColor = Color.Blue;

    Name
    Name property represents a unique name of a RadioButton control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a RadioButton control.
    dynamicRadioButton.Name = "DynamicRadioButton";
    string name = dynamicRadioButton.Name;

    Text and TextAlign
    Text property of a RadioButton represents the current text of a RadioButton control. The TextAlign property represents text alignment that can be Left, Center, or Right. The following code snippet sets the Text and TextAlign properties and gets the size of a RadioButton control.
    dynamicRadioButton.Text = "I am a Dynamic RadioButton";
    dynamicRadioButton.TextAlign = ContentAlignment.MiddleCenter;

    Font
    Font property represents the font of text of a RadioButton control. If you click on the Font property in Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.
    dynamicRadioButton.Font = new Font("Georgia", 16);

    Appearance
    Appearance property of RadioButton can be used to set the appearance of a RadioButton to a Button or a RadioButton. The Button look does not have a round select option. The following property makes a RadioButton look like a Button control.
    dynamicRadioButton.Appearance = Appearance.Button;

    Image in RadioButton
    The Image property of a RadioButton control is used to set the background as an image. The Image property needs an Image object. The Image class has a static method called FromFile that takes an image file name with full path and creates an Image object.
    You can also align image and text. The ImageAlign and TextAlign properties of RadioButton are used for this purpose.
    The following code snippet sets an image as a RadioButton background.

    dynamicRadioButton.Image = Image.FromFile(@"C:\Images\Dock.jpg");
    dynamicRadioButton.ImageAlign = ContentAlignment.MiddleRight;
    dynamicRadioButton.FlatStyle = FlatStyle.Flat;

    RadioButton States
    A typical RadioButton control has two possible states €“ Checked and Unchecked. Checked state is when the RadioButton has check mark on and Unchecked is when the RadioButton is not checked. Typically, we use a mouse to check or uncheck a RadioButton.
    Checked property is true when a RadioButton is in checked state.
    dynamicRadioButton.Checked = true;

    Usually, we check if a RadioButton is checked or not and decide to take an action on that state something like following code snippet.
    if (dynamicRadioButton.Checked)
    {
    // Do something when RadioButton is checked
    }
    else
    {
    // Do something here when RadioButton is not checked
    }


    AutoCheck property represents whether the Checked or CheckState values and the RadioButton's appearance are automatically changed when the RadioButton is clicked. By default this property is true but if set to false.
    dynamicRadioButton.AutoCheck = false;

    TextBox
    We can create a TextBox control using a Forms designer at design-time or using the TextBox class in code at run-time (also known as dynamically).
    To create a TextBox control at design-time, you simply drag and drop a TextBox control from Toolbox to a Form in Visual Studio. After you drag and drop a TextBox on a Form, the TextBox looks like Figure. Once a TextBox is on the Form, you can move it around and resize it using mouse and set its properties and events.

    Figure


    Some properties of TextBox

    After you place a TextBox control on a Form, the next step is to set properties.
    The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item.

    Location, Height, Width, and Size
    The Location property takes a Point that specifies the starting position of the TextBox on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a TextBox control.
    // Set TextBox properties
    dynamicTextBox.Location = new Point(20, 150);
    dynamicTextBox.Height = 40;
    dynamicTextBox.Width = 300;

    Multiline TextBox
    By default, a TextBox control accepts input in a single line only. To make it multi-line, you need to set Multiline property to true. By default, the Multiline property is false.
    When you drag and drop a TextBox control from Toolbox to a Form, you cannot change the height of a TextBox control.




    But if you select a TextBox control and click on Tasks handle and check MultiLine CheckBox, you will see height resizing grip handles are available on a TextBox and you can resize the height of a control.





    You can do this dynamically by setting Multiline property to true.
    // Make TextBox multiline
    dynamicTextBox.Multiline = true;

    Background, Foreground, BorderStyle
    BackColor and ForeColor properties are used to set background and foreground color of a TextBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.
    Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.
    // Set background and foreground
    dynamicTextBox.BackColor = Color.Red;
    dynamicTextBox.ForeColor = Color.Blue;
    You can also set borders style of a TextBox by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values €“ FixedSingle, Fixed3D, and None. The default value of border style is Fixed3D. The following code snippet sets the border style of a TextBox to FixedSingle.
    dynamicTextBox.BorderStyle = BorderStyle.FixedSingle;

    Name
    Name property represents a unique name of a TextBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a TextBox control.
    dynamicTextBox.Name = "DynamicTextBox";
    string name = dynamicTextBox.Name;

    Text, TextAlign, and TextLength
    Text property of a TextBox represents the current text of a TextBox control. The TextAlign property represents text alignment that can be Left, Center, or Right. The TextLength property returns the length of a TextBox contents.
    The following code snippet sets the Text and TextAlign properties and gets the size of a TextBox control.
    dynamicTextBox.Text = "I am Dynamic TextBox";
    dynamicTextBox.TextAlign = HorizontalAlignment.Center;
    int size = dynamicTextBox.TextLength;

    Font
    Font property represents the font of text of a TextBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.
    dynamicTextBox.Font = new Font("Georgia", 16);

    Password Character and Character Casing
    PasswordChar property is used to apply masking on a TextBox when you need to use it for a password input and do now what password to be readable. For example, you can place a star (*) for password characters.
    The following code snippet sets a dollar ($) symbol as any character entered in a TextBox.
    dynamicTextBox.PasswordChar = '$';
    UseSystemPasswordChar property is used to full default system password If the UseSystemPasswordChar is set to true, the default system password character is used and any character set by PasswordChar is ignored.
    CharacterCasing property of TextBox sets the case of text in a TextBox, It has three values €“ Upper, Lower, and Normal.
    dynamicTextBox.CharacterCasing = CharacterCasing.Upper;

    Maximum Length
    You can restrict number of characters in a TextBox control by setting MaxLength property. The following code snippet sets the maximum length of a TextBox to 50 characters.
    dynamicTextBox.ReadOnly = true;
    dynamicTextBox.MaxLength = 50;

    Cut, Copy, Paste, Undo Operations in TextBox
    TextBox class provides Cut, Copy, Paste, and Undo methods to cut, copy, paste, and undo clipboard operations. The following code snippet shows how to use Cut, Copy, Paste, and Undo methods.
    private void cutToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (textBox1.SelectionLength > 0)
    textBox1.Cut();
    }

    private void copyToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (textBox1.SelectionLength > 0)
    textBox1.Copy();
    }

    private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
    {
    textBox1.Paste();
    }
    }

    private void undoToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (textBox1.CanUndo)
    {
    textBox1.Undo();
    textBox1.ClearUndo();
    }
    }


    RichTextBox
    A RichTextBox control is an advanced text box that provides text editing and advanced formatting features including loading rich text format (RTF) files.
    In this article, I will demonstrates how to create and use various features of the Windows Forms RichTextBox control.

    Creating a RichTextBox
    We can create a RichTextBox control using a Forms designer at design-time or using the RichTextBox class in code at run-time.
    To create a RichTextBox control at design-time, you simply drag and drop a RichTextBox control from the Toolbox onto a Form in Visual Studio. Once a RichTextBox is added to a Form, you can move it around and resize it using the mouse and set it's properties and events.

    Setting RichTextBox Properties

    After you place a RichTextBox control on a Form, the next step is to set properties.
    The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item.

    Location, Height, Width, and Size
    The Location property takes a Point that specifies the starting position of the RichTextBox on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a RichTextBox control.
    dynamicRichTextBox.Location = new Point(20, 20);
    dynamicRichTextBox.Width = 300;
    dynamicRichTextBox.Height = 200;

    Background, Foreground, BorderStyle
    BackColor and ForeColor properties are used to set the background and foreground color of a RichTextBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.
    Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.
    // Set background and foreground
    dynamicRichTextBox.BackColor = Color.Red;
    dynamicRichTextBox.ForeColor = Color.Blue;

    You can also set the borders style of a RichTextBox by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values €“ FixedSingle, Fixed3D, and None. The default value of border style is Fixed3D. The following code snippet sets the border style of a RichTextBox to FixedSingle.
    dynamicRichTextBox.BorderStyle = BorderStyle.FixedSingle;

    Name
    The Name property represents a unique name of a RichTextBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a RichTextBox control.
    dynamicRichTextBox.Name = "DynamicRichTextBox";

    Text and TextLength
    The Text property of a RichTextBox represents the current text of a RichTextBox control. The TextLength property returns the length of a RichTextBox contents.
    The following code snippet sets the Text and TextAlign properties and gets the size of a RichTextBox control.
    dynamicRichTextBox.Text = "I am Dynamic RichTextBox";
    int size = dynamicRichTextBox.TextLength;


    Append Text
    One way to append text to a RichTextBox is simply set Text property to current text plus new text you would want to append something like this.
    RichTextBox1.Text += " Appended text";
    RichTextBox also has the ApendText method to do the same. The AppendText method appends text at the end of a RichTextBox. The following code snippet uses AppendText method to append text to the RichTextBox1 contents.
    RichTextBox1.AppendText(" Appended text");

    Font
    Font property represents the font of text of a RichTextBox control. If you click on the Font property in the Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.
    dynamicRichTextBox.Font = new Font("Georgia", 16);

    Maximum Length
    You can restrict the number of characters in a RichTextBox control by setting MaxLength property. The following code snippet sets the maximum length of a RichTextBox to 50 characters.
    dynamicRichTextBox.ReadOnly = true;
    dynamicRichTextBox.MaxLength = 50;

    Selection in RichTextBox
    The SelectedText property returns the selected text in a RichTextBox control.
    string selectedText = dynamicRichTextBox.SelectedText;
    You may also use SelectionStart and SelectionLength properties to get and set the selected text in a RichTextBox. The SelectionStart property represents the starting index of the selected text and SelectionLength property represents the number of characters to be selected after the starting character. The following code snippet sets the selection on a RichTextBox.
    dynamicRichTextBox.SelectionStart = 10;
    dynamicRichTextBox.SelectionLength = 20;

    Clear, SelectAll and DeselectAll
    The Clear method removes the contents of a RichTextBox. The following code snippet uses Clear method to clear the contents of a RichTextBox.
    RichTextBox1.Clear();
    RichTextBox class provides SelectAll and DeselectAll methods to select and deselect all text of a RichTextBox control. The following code snippet shows how to use SelectAll and DeselectAll methods.
    private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (RichTextBox1.TextLength > 0)
    RichTextBox1.SelectAll();
    }

    private void deselectAllToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (RichTextBox1.TextLength > 0)
    RichTextBox1.DeselectAll();
    }



    Cut, Copy, Paste, Undo Operations in RichTextBox
    RichTextBox class provides Cut, Copy, Paste, and Undo methods to cut, copy, paste, and undo clipboard operations. The following code snippet shows how to use Cut, Copy, Paste, and Undo methods.
    private void cutToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (RichTextBox1.SelectionLength > 0)
    RichTextBox1.Cut();
    }

    private void copyToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (RichTextBox1.SelectionLength > 0)
    RichTextBox1.Copy();
    }

    private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
    {
    RichTextBox1.Paste();
    }
    }

    private void undoToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (RichTextBox1.CanUndo)
    {
    RichTextBox1.Undo();
    RichTextBox1.ClearUndo();
    }
    }

    Label
    To create a Label control at design-time, you simply drag and drop a Label control from Toolbox to a Form. After you drag and drop a Label on a Form. The Label looks like Figure. Once a Label is on the Form, you can move it around and resize it using mouse and set its properties and events.



    Setting Label Properties
    After you place a Label control on a Form, the next step is to set properties.
    The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure.

    Name
    Name property represents a unique name of a Label control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a Label control.
    dynamicLabel.Name = "DynamicLabel";
    string name = dynamicLabel.Name;

    Location, Height, Width, and Size
    The Location property takes a Point that specifies the starting position of the Label on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a Label control.
    dynamicLabel.Location = new Point(20, 150);
    dynamicLabel.Height = 40;
    dynamicLabel.Width = 300;

    Background, Foreground, BorderStyle
    BackColor and ForeColor properties are used to set background and foreground color of a Label respectively. If you click on these properties in Properties window, the Color Dialog pops up.
    Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.
    dynamicLabel.BackColor = Color.Red;
    dynamicLabel.ForeColor = Color.Blue;
    You can also set borders style of a Label by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values €“ FixedSingle, Fixed3D, and None. The default value of border style is Fixed3D. The following code snippet sets the border style of a Label to FixedSingle.
    dynamicLabel.BorderStyle = BorderStyle.FixedSingle;

    Font
    Font property represents the font of text of a Label control. If you click on the Font property in Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.
    dynamicLabel.Font = new Font("Georgia", 16);

    Text and TextAlign, and TextLength
    Text property of a Label represents the current text of a Label control. The TextAlign property represents text alignment that can be Left, Center, or Right. The TextLength property returns the length of a Label contents.
    The following code snippet sets the Text and TextAlign properties and gets the size of a Label control.
    dynamicLabel.Text = "I am Dynamic Label";
    dynamicLabel.TextAlign = HorizontalAlignment.Center;
    int size = dynamicLabel.TextLength;

    Append Text
    We can append text to a Label by simply setting Text property to current text plus new text you would want to append something like this.
    dynamicLabel.Text += " Appended text";

    Image in Label
    The Image property of a Label control is used to set a label background as an image. The Image property needs an Image object. The Image class has a static method called FromFile that takes an image file name with full path and creates an Image object.
    You can also align image and text. The ImageAlign and TextAlign properties of Button are used for this purpose.
    The following C# code snippet sets an image as a Label background.

    dynamicLabel.Image = Image.FromFile(@"C:\Images\Dock.jpg");
    dynamicLabel.ImageAlign = ContentAlignment.MiddleRight;
    dynamicLabel.TextAlign = ContentAlignment.MiddleLeft;
    dynamicLabel.FlatStyle = FlatStyle.Flat;

    PictureBox

    PictureBox class represents a PictureBox control. The following code snippet creates a PictureBox, sets its width and height and adds control to the Form by calling Controls.Add() method.
    Code:
    PictureBox imageControl = new PictureBox();
    imageControl.Width = 400;
    imageControl.Height = 400;
    Controls.Add(imageControl);

    Display an Image
    Image property is used to set an image to be displayed in a PictureBox control. The following code snippet creates a Bitmap from an image and sets the Image property of PictureBox control. Code also sets the Dock property of PictureBox.
    Code:
    private void DisplayImage()
    {
    PictureBox imageControl = new PictureBox();
    imageControl.Width = 400;
    imageControl.Height = 400;
    Bitmap image = new Bitmap("C:\\Images\\Creek.jpg");
    imageControl.Dock = DockStyle.Fill;
    imageControl.Image = (Image)image;
    Controls.Add(imageControl);
    }

    The output looks like Figure where an image is displayed.


    SizeMode
    SizeMode property is used to position an image within a PictureBox. It can be Normal, StretchImage, AutoSize, CenterImage, and Zoom. The following code snippet sets SizeMode property of a PictureBox control.
    C# Code:
    imageControl.SizeMode = PictureBoxSizeMode.CenterImage;
    The MenuStrip class is the foundation of menus functionality in Windows Forms. If you have worked with menus in .NET 1.0 and 2.0, you must be familiar with the MainMenu control. In .NET 3.5 and 4.0, the MainMenu control is replaced with the MenuStrip control.
    MenuStrip

    We can create a MenuStrip control using a Forms designer at design-time or using the MenuStrip class in code at run-time or dynamically.
    To create a MenuStrip control at design-time, you simply drag and drop a MenuStrip control from Toolbox to a Form in Visual Studio. After you drag and drop a MenuStrip on a Form, the MenuStrip1 is added to the Form and looks like Figure. Once a MenuStrip is on the Form, you can add menu items and set its properties and events.

    Figure
    Creating a MenuStrip control at run-time is merely a work of creating an instance of MenuStrip class, set its properties and adds MenuStrip class to the Form controls.
    First step to create a dynamic MenuStrip is to create an instance of MenuStrip class. The following code snippet creates a MenuStrip control object.

    Setting MenuStrip Properties

    After you place a MenuStrip control on a Form, the next step is to set properties.
    The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item.

    Name
    Name property represents a unique name of a MenuStrip control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a MenuStrip control.
    Tool Strip
    ToolStrip control provides functionality of a Windows toolbar controls in Visual Studio 2010. ToolStrip class represents a ToolStrip control in Windows Forms and serves as a base class of MenuStrip, StatusStrip, and ContextMenuStrip classes.
    We can create a ToolStrip control at design-time using Visual Studio designer or using the ToolStrip class at run-time.

    Using Designer
    To create a ToolStrip control at design-time, simply drag and drop a ToolStrip control from Toolbox onto a Form. By default, a ToolStrip control is docked at the top of the Form. We can change docking and other properties using the Tasks control as shown in Figure.

    Figure
    Next step is to set ToolStrip control properties. We can set properties by calling Properties window if a control using Right click on the control and selecting Properties menu item or simply hit F4. Figure 2 shows Properties window where I set BackColor to green and GripStyle to Visible.

    Figure
    A ToolStrip control is nothing but a container without adding its child controls. A ToolStrip control is capable of hosting Button, Label, SplitButton, DropDownButton, Separator, ComboBox, TextBox and ProgressBar controls.
    Now let's add a few controls to ToolStrip control.
    If you click on little dropdown handle on a ToolStrip control in designer, you will see a list of possible controls (See Figure 3) that can be added to a ToolStrip. To add a control, simply select that control and it will be added to the ToolStrip control.

    Figure
    Another way to add controls to a ToolStrip control is by using the Items property.
    Click on the Items property and you will see Item Collection Editor that looks like Figure. We are going to add a Button, a TextBox, and a Label control to ToolStrip with a few separators.

    Figure
    If you need to reposition controls, you can simply use up and down arrows.
    Here is a good part. Once these controls are added to a ToolStrip control, the all act as individual controls and you can access them by using their Name property anywhere in the code.
    Now let's create a sample. We are going to add three Button controls, three separators and a Label control as you can see in Figure.

    Figure
    Now next we are going to set an icon for the Button controls by setting Image property of Button. See Figure.



    Figure
    Once you click on the browse option to browse an image, Resource editor window pops up where you can import an image. Click on Import button and browse an image file.

    Figure 7
    We set three icons for all three buttons and the ToolStrip looks like Figure.

    Figure
    Next step is to set the button click event handler. It is easy. Just double click or use Events window and set click event handlers for all three buttons.

    Three button click event handlers look like following where we set Text property of Label.
    private void toolStripButton1_Click_1(object sender, EventArgs e)
    {
    toolStripLabel1.Text = "Button1 is clicked";
    }

    private void toolStripButton2_Click_1(object sender, EventArgs e)
    {
    toolStripLabel1.Text = "Button2 is clicked";
    }

    private void toolStripButton3_Click_1(object sender, EventArgs e)
    {
    toolStripLabel1.Text = "Button3 is clicked";
    }

    Now if you run the project and click on Buttons, you will see something like Figure.


    Figure

    Checked List Box
    CheckedListBox presents several items in a list. Each item is checkable—the user can check a box. The CheckedListBox control in Windows Forms is a way to make longer, dynamic checkable lists.

    Example

    To start, create a Windows Forms program in Visual Studio. Next, please open the Toolbox and double-click on the CheckedListBox item. A new control is created.
    From here, you can right-click on the CheckedListBox and select Properties to adjust properties and also add event handlers. In this first example, you need to add the Form1_Load event handler by double-clicking on the form as well.
    Event
    Example that add items to CheckedListBox
    using System;
    using System.Windows.Forms;
    namespace WindowsFormsApplication25
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    var items = checkedListBox1.Items;
    items.Add("Perls");
    items.Add("Checked", true);
    }
    }
    }
    Adding items dynamically. You can add items to the CheckedListBox at design time. But you can also add items dynamically at runtime. You must use the checkedListBox1.Items property and the Add or AddRange methods on that.
    The CheckedListBox will instantly detect the new items and display them. This makes programs responsive to user actions.
    SelectedIndex: Another useful event handler on the CheckedListBox is the SelectedIndexChanged handler. You might use this event handler to display some useful text in the UI when an item is selected.
    Tip:You must check the SelectedIndex property for the value -1 to prevent an IndexOfOutRangeException.
    IndexOutOfRangeException
    Example that uses SelectedIndex Property
    using System;
    using System.Windows.Forms;
    namespace WindowsFormsApplication25
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    // Get selected index, and then make sure it is valid.
    int selected = checkedListBox1.SelectedIndex;
    if (selected != -1)
    {
    this.Text = checkedListBox1.Items[selected].ToString();
    }
    }
    }
    }

    Items:
    It is also possible to edit the Items that are shown in the CheckedListBox at design time. In Visual Studio, select Properties and then Items on the CheckedListBox instance. You will get the String Collection Editor.
    This functionality is the same in Visual Studio 2010 as well. Use a line break after each separate item.

    CheckOnClick
    One useful property is the CheckOnClick property. By default, this is set to False. When False, the user must click a second time after an item is selected to check the box. When True, the user must only click once to check a box.
    IntegralHeight
    It is possible to use the IntegralHeight property on the CheckedListBox to ensure that no partial items are shown. Depending on the structure of your user interface, this may be desirable.
    Note: Please see the detailed article on IntegralHeight. This property may improve the design of your program.
    IntegralHeight Property: Windows Forms

    Enabled:
    When you set Enabled to False, the entire control is disabled. With the CheckedListBox, setting Enabled to False will gray out all the items in the control, and also make them unclickable and unselectable.

    ThreeDCheckBoxes
    By default, the CheckedListBox has checkboxes that have a flat, single-pixel border. For some programs, a more three-dimensional appearance may be desirable. To solve this, you can set the ThreeDCheckBoxes property to true.

    Background
    Controls in Windows Forms also have the BackColor and ForeColor properties available. The BackColor property adjusts the background of the controls, while the ForeColor adjusts the text color.
    Panel
    Panel creates a grouping of controls. This control provides a simple frame for putting sub-controls inside. These sub-controls include buttons and text boxes. It further provides an optional border and ways to change its visibility.


    To start, please open your Visual Studio Windows Forms project and open the Toolbox, where you can then double-click on the Panel icon. Next, try right-clicking on the Panel in the form and selecting Properties.
    You might want to change the BorderStyle, which you can set to Fixed3D to make the Panel look like the example screenshot.
    Sub-controls in Panel. The entire point of the Panel is to provide a visual and logical grouping for controls. To add some controls to the Panel, drag them to the inner part of the Panel in Visual Studio.
    When the controls are inside the Panel, they will be affected by the Enabled property of the Panel and the Visible property.
    Note:In the example, we added two Button controls to the inside of the Panel control.
    Borders

    The default Panel does not have a visible border. This is ideal for some programs. But for others, using the Fixed3D or FixedSingle border style is more appropriate. This may also look better.
    Review:As you may know from other controls, FixedSingle is a single dark line while the Fixed3D style is an inset, shaded border.
    Enabled
    What happens when you set the Enabled property of the Panel to False? All of the enclosed controls in the Panel, such as buttons or text boxes, will become inactive and grayed out. They cannot be used by the mouse or the keyboard.
    Instead of dealing with many text boxes or buttons separately, you can change many controls' states at once with the Panel this way.
    Setting Visible property. Also, the Visible property of the Panel affects all the enclosed controls. So if you set the Visible property to False, you will hide all of the sub-controls inside the Panel as well as the Panel itself.
    Flow Layout Panel
    FlowLayoutPanel simplifies how controls are arranged. With FlowLayoutPanel, we have the controls flow like text from left to right, top to bottom, or the opposite directions. No pixel-based positioning is required for these controls.

    Add
    To get started, please open your Windows Forms program. Now add a FlowLayoutPanel instance to your Form. You can do this by dragging the FlowLayoutPanel from the Toolbox to the Form.
    Next:Add some sub-controls by dragging controls such as Button, Label, CheckBox and TextBox to the inner part of the FlowLayoutPanel.
    Anchor
    It is usually a good idea to anchor your FlowLayoutPanel to other parts of the Form. I typically anchor controls to the top, right, left and bottom of the form to ensure they resize when the window is resized by the user or other code.
    Anchor in Windows Forms
    FlowDirection
    The unique feature of the FlowLayoutPanel is its support for flowing in different directions. The default flow direction is left to right, like English text. The introductory screenshot in this article shows the FlowDirection of TopDown.
    Tip:For the FlowDirection property, you can also use RightToLeft and BottomUp values.

    AutoScroll
    In some programs, the FlowLayoutPanel may end up being too small to show all the controls. In this case, you can set the AutoScroll property to True. The FlowLayoutPanel will display scrollbars when the controls overflow.


    Table Layout Panel

    TableLayoutPanel positions controls. We require an attractive and functional GUI that resizes properly when users change the size of the window.
    First, to make a TableLayoutPanel, expand the toolbox on the left side. Double click on the TableLayoutPanel icon in the left, and then open the Properties pane on the right.
    Four-pane panel. You should see a four-pane panel. You will need to modify the number of columns and rows. And then you can change row spans and column spans.
    Properties. Anchor is used to align, expand, or fill a control. Column is used to specify number of columns. Row specifies number of rows—add one to get a new row on the bottom.
    Anchor. When you click on the space next to Anchor in the Property pane on the right, you will see a box that looks like a +. Click on the rectangles to anchor to that edge.
    TextBox. To create a multi-line TextBox that fills the entire cell, set the TextBox as multiline. Add Top and Bottom in the Anchor menu by clicking on the up and down parts of the +.
    Solving layout problems. TableLayoutPanel may solve many of the control alignment problems you have. TableLayoutPanel is flexible and can greatly enhance interfaces.
    However, it requires a planning step before dragging controls to your form. TableLayoutPanel is easier to maintain. This planning step is worth taking.

    A rigid layout makes life hard for you, as the designer, and the user who is trying to use the program in a slightly different configuration. TableLayoutPanel eliminates these problems.
    Tool Strip Container
    ToolStripContainer adds user interface functionality. It serves as a way to allow ToolStrips (which contain buttons or other controls) to be dragged around the edges of a Form. We specify how ToolStrips can be located and arranged.

    Start: To begin, open your Windows Forms project and drag the ToolStripContainer to the Form. Next, you can optionally Dock the ToolStripContainer in the Form. Please see the next section.
    When you first add the oolStripContainer to your project, try clicking on the "Dock Fill in Form" link in Visual Studio 2010. This will expand the ToolStripContainer to reach the four sides of the enclosing form.
    Blue arrows
    To enable the ToolStripContainer on a certain side, click the blue arrow on that side to expand it. If you add a ToolStrip to that side, try clicking the blue arrow again: the area will expand and more controls can be placed there.


    Add ToolStrip
    Inside the ToolStripContainer, you can add ToolStrip instances. Make sure you use the blue arrows to expand the side you want to use. Then, drag a ToolStrip to the top, right, left or bottom area you expanded.
    The ToolStrip will be located in that area by default. A user will be able to drag it to another area.
    Properties
    With the ToolStripContainer, you can address the top, right, left and bottom panels through your C# code. If you have some ToolStrips located there, you can use these properties to get references to them.
    Panel types
    1. TopToolStripPanel
    2. RightToolStripPanel
    3. BottomToolStripPanel
    4. LeftToolStripPanel

    Visibility properties. By assigning a Visibility property to false, you make it so a ToolStrip cannot be dragged to that side. By default, all sides have a Visibility of true. Here are the properties.
    Panel Visible properties
    • TopToolStripPanelVisible
    • RightToolStripPanelVisible
    • BottomToolStripPanelVisible
    • LeftToolStripPanelVisible

    List View
    List View provides a useful view of items with icons. This view is similar to those found in file system managers such as Windows Explorer. By providing a lot of functionality built-in, we avoid complex layout routines.


    Let's begin by adding a ListView control to our Windows Forms. Please open the Toolbox and then double-click on the ListView entry. Next, you will want to set the important properties and event handlers on the ListView instance you created. Right-click on it in Visual Studio and select Properties to open this dialog.
    View
    There are many different settings for the View property on the ListView. This property determines how the icons in the control are displayed. In the top screenshot in this article, the setting is LargeIcon. Next we see the SmallIcon setting.

    Next, we see the List setting on the View property. You can see that the icons are arranged in a vertical line on the left of the control region.

    Finally, there is a Tile setting. Similar to the tile setting in Windows Explorer, this setting adds whitespace, which may help the visual appearance of the control.

    Items
    The Items property is the most important one on the ListView, as it enables you to add the data entries to the ListBox. You can add to the Items property by double-clicking on the Items entry and adding Items one-by-one in the ListViewItem Collection Editor. More useful, you can add elements dynamically through C# code, as in the Load event handler on the enclosing form.

    What is ADO.NET ?

    ADO.NET is the new database technology of the .NET (DotNet) platform, and it builds on ADO (ActiveX Data Objects). ADO is a language-neutral object model that is the keystone of Microsoft's Universal Data Access strategy. ADO.NET defines DataSet and DataTable objects which are optimized for moving disconnected sets of data across intranets and Internets, including through firewalls. Its also including the traditional Connection and Command objects, as well as an object called a DataReader that resembles a forward-only, read-only ADO record set. If you create a new application your application requires most of the time some form of data access.

    ADO.NET provides data access services in the Microsoft .NET Platform. You can use ADO.NET to access data by using the new .NET Framework data providers which are
    – Data Provider for SQL Server(System.Data.SqlClient).
    – Data Provider for OLEDB(System.Data.OleDb).
    – Data Provider for ODBC(System.Data.Odbc).
    – Data Provider for Oracle(System.Data.OracleClient).

    There are two central components of ADO.NET classes:
    the DataSet, and the .NET Framework Data Provider.

    Data Provider is a set of components including the
    Connection object (SqlConnection, OleDbConnection, OdbcConnection, OracleConnection),
    the Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand),
    the DataReader object (SqlDataReader, OleDbDataReader,OdbcDataReader, OracleDataReader),
    and the DataAdapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter).

    DataSet object represents a disconnected cache of data which is made up of DataTables and DataRelations that represent the result of the command.

    The ADO.NET Object Model



    Connection to a ADO.NET database
    Before working with a database, you have to add the OleDb .NET Data Provider namespace, by placing the following at the start of your code module:
    using System.Data.OleDb;


    Similarly for the SqlClient .NET Data Provider namespace:
    using System.Data.SqlClient;
    the using statement should be positioned first in your code. Now we have to declare a connection string pointing to a MS Access database "PersonDatabase.mdb".
    Public string conString=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\PersonDatabase.mdb";
    the database should be in the specified path, otherwise you should change the path accordingly.
    The next step is to create an OleDbConnection object. We pass then the connection string to this OleDbConnection object.
    You can code now to create a new ADO.NET Connection object in order to connect to an OLE DB provider database.
    OleDbConnection con = new OleDbConnection (conString);


    DataSet

    The DataSet is similar to an array of disconnected Recordset objects. It supports disconnected data access and operations, allowing greater scalability because you no longer have to be connected to the database all the time. DataSet is a copy of a extracted data being downloaded and cached in the client system.

    DataSet object is made up of 2 objects:
    -DataTableCollection Object containing null or multiple DataTable objects (Columns, Rows, Constrains)
    -DataRelationCollection Object containing null or multiple DataRelation objects
    which establishes a parent/child relation between two DataTable objects.
    //Create a DataSet
    DataSet dset = new DataSet();

    There are two types of DataSets:
    1. Typed dataset
    2. Untyped dataset

    Typed dataset is derived from the base DataSet class and then uses information in an XML Schema file (.xsd file) in order to generate a new class. Information from the schema (tables, columns, and so on) is generated and compiled into this new dataset class as a set of first-class objects and properties. Typed dataset is easier to read.

    Untyped dataset is not defined by a schema, instead, you have to add tables, columns, and other elements to it yourself, either by setting properties at design time or by adding them at run time. A dataset is a container; therefore, you have to fill it with data.


    You can populate a dataset in a variety of ways;
    # by using Fill method
    # by creating DataRow objects and adding them to the table's Rows collection(only at run time).
    # Read an XML document or stream into the dataset
    # Merge (copy) the contents of another dataset

    DataAdapter

    DataAdapter object is like a bridge that links the database and a Connection object with the ADO.NET-managed DataSet object through its SELECT and action query Commands.
    It specifies what data to move into and out of the DataAdapter. Often this takes the form of references to SQL statements or stored procedures that are invoked to read or write to a database.
    The DataAdapter provides four properties that allow us to control how updates are made to the server:
    SelectCommand, UpdateCommand, InsertCommand, and DeleteCommand.
    The four properties are set to Command objects that are used when data is manipulated.
    The DataAdapter includes 3 main methods:


    - Fill (populates a DataSet with data)
    - FillSchema (queries the database for schema information that is necessary to update)
    - Update (to change the database DataAdapter calls the DeleteCommand, the InsertCommand and the UpdateCommand property)


    For instance , when we call the DataAdapter's Fill method to retrieve data from a data source and pour it into a DataSet, the Command object in the SelectCommand property is used. The DataAdapter is the gatekeeper that sits between our DataSet and the data source.

    //Create an instance of a OleDbDataAdapter by passing OleDbConnection object and select.. query
    OleDbDataAdapter dAdapter = new OleDbDataAdapter ("select * from PersonTable", con );


    //fill the DataSet with records from the table "PersonTable"
    dAdapter.Fill(dSet,"PersonTable");

    Commands

    A command is, in its simplest form, a string of text containing SQL statements that is to be issued to the database. A command could also be a stored procedure, or the name of a table that will return all columns and all rows from that table (in other words, a SELECT *-style clause).

    Executing Commands
    After you have defined the command, you need to execute it. A number of ways exist to issue the statement, depending on what you expect to be returned (if anything) from that command. The > provider>> ommand classes provide the following execute methods:
    • ExecuteNonQuery() — Executes the command but does not return any output
    • ExecuteReader() — Executes the command and returns a typed IDataReader
    • ExecuteScalar() — Executes the command and returns a single value

    ExecuteNonQuery()

    This method is commonly used for UPDATE, INSERT, or DELETE statements, where the only returned value is the number of records affected. This method can, however, return results if you call a stored procedure that has output parameters:

    ExecuteReader()

    This method executes the command and returns a typed data reader object, depending on the provider in use. The object returned can be used to iterate through the record(s) returned.

    ExecuteScalar()
    On many occasions, it is necessary to return a single result from a SQL statement, such as the count of records in a given table, or the current date/time on the server

    Data Reader
    Retrieving data using a DataReader involves creating an instance of the Command object and then creating a DataReader by calling Command.ExecuteReaderto retrieve rows from a data source. The following example illustrates using a DataReader where reader represents a valid DataReader and command represents a valid Command object.

    Reader = command.ExecuteReader();



    You use the Read method of the DataReader object to obtain a row from the results of the query. You can access each column of the returned row by passing the name or ordinal reference of the column to the DataReader. However, for best performance, the DataReader provides a series of methods that allow you to access column values in their native data types (GetDateTime, GetDouble, GetGuid, GetInt32, and so on). For a list of typed accessor methods for data provider-specific DataReaders, see OleDbDataReader and SqlDataReader. Using the typed accessor methods, assuming the underlying data type is known, reduces the amount of type conversion required when retrieving the column value.

    The following code example iterates through a DataReader object, and returns two columns from each row.

    static void HasRows(SqlConnection connection)
    {
    using (connection)
    {
    SqlCommand command = new SqlCommand(
    "SELECT CategoryID, CategoryName FROM Categories;",
    connection);
    connection.Open();

    SqlDataReader reader = command.ExecuteReader();

    if (reader.HasRows)
    {
    while (reader.Read())
    {
    Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
    reader.GetString(1));
    }
    }
    else
    {
    Console.WriteLine("No rows found.");
    }
    reader.Close();
    }
    }The DataReader provides an unbuffered stream of data that allows procedural logic to efficiently process results from a data source sequentially. TheDataReader is a good choice when retrieving large amounts of data because the data is not cached in memory.

    Last edited by ajaytopgun; 14th October 2015 at 04:23 PM.

Tags for this Thread