Top Banner

of 36

2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

Apr 03, 2018

Download

Documents

kris2tmg
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    1/36

    2Windows Forms Controls:

    RadioButton, CheckBox,ListBox, CheckedListBox,

    and ComboBox

    If you need an Immediate Solution to: See page:

    Using the RadioButton Control 42

    Using the CheckBox Control 45

    Using the ListBox Control 49

    Using the CheckedListBox Control 56

    Using the ComboBox Control 59

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    2/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    32

    In Depth

    In the previous chapter, you learned about some of the commonly used controls, such asButton

    ,Label

    ,TextBox, RichTextBox, and MaskedTextBox. This chapter describes some of the standard Windows Formscontrols, RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox. These controls form the basic layoutof an application using which users interact with the application. You would call these controls as selectioncontrols since all of them are primarily used for selection purpose. The RadioButton control is used in a situationwhere you want to select only one option from the group of options; whereas, the CheckBox control allows youto select multiple options from the group. The ListBox control lists all the items and allows you to select theitems from the list. The CheckedListBox control is similar to the ListBox control; in addition, it displays checkboxes beside every item in the list. Instead of selecting the item, you can select the check box of that particularitem you want to select the CheckedListBox control. The ComboBox control is similar to the ListBox control; thedifference is that the ComboBox control displays the items as the drop-down list.

    The basic idea of this chapter is to help you decide which control to use for which purpose and provide yousome idea about the most commonly used properties, methods, and events of the control. This chapter describesthe general purpose of using the controls. The chapter starts with the discussion on the controls- RadioButton,

    CheckBox, ListBox, CheckedListBox, and ComboBox- and also lists their properties, methods, and events.Next, you learn about the practical implementation of these controls in the Immediate Solution of the chapter.

    Lets start our discussion with the RadioButton control.

    The RadioButton ControlA RadioButton control, also known as an option button, is used to select one option from a set of options.Radio buttons and check boxes may appear similar to you except for one main difference. A check box can workindependently; whereas, radio buttons always work in groups. This means that whenever you select one radiobutton from a group of radio buttons, the other radio buttons in the group automatically get deselected. Incontrast, you can select any number of check boxes from a list of check boxes. In other words, radio buttons areused for single-select choices, while check boxes are used for multiple-select options. Figure 2.1 shows radiobuttons as they appear at design time:

    Figure 2.1: Showing the Radio Buttons

    You can display text, images, or both simultaneously on the RadioButton controls. You can use the Checkedproperty of the control to get or set the state of a radio button. The appearance of the radio button may bealtered to appear as a toggle-style button or as a standard radio button by setting the Appearance property ofthe RadioButton control. In addition, if you want to place more than one group of radio buttons on the sameform, you must place the radio buttons in different container controls, such as GroupBox or Panel control.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    3/36

    In Depth

    33

    Following is the class hierarchy of the RadioButton class:

    System.Object

    System.MarshalByRefObject

    System.ComponentModel.Component

    System.Windows.Forms.ControlSystem.Windows.Forms.ButtonBase

    System.Windows.Forms.RadioButton

    Table 2.1 lists the important properties of the RadioButton class:

    Table 2.1: Showing the Noteworthy Properties of the RadioButton Class

    Property Description

    Appearance Retrieves or sets the value for this property that determines the appearance ofthe radio button.

    AutoCheck Retrieves or sets a value indicating whether or not the Checked value and theappearance of the control should automatically change when the radio button isclicked.

    CheckAlign Retrieves or sets the location of the check box portion of the radio button. Aradio button consists of a check box portion and a text. The check box portion

    determines whether the radio button is checked or unchecked and the text isused to set a caption on the radio button. When you set the CheckAlignproperty of the RadioButton control, the location of the check box portionchanges to the value assigned and the text remains as it is.

    Checked Retrieves or sets a value indicating whether the radio button is clicked.

    Enabled Retrieves or sets a value indicating whether or not the user can select the radiobutton.

    Text Retrieves or sets the caption for a radio button.

    TextAlign Retrieves or sets the alignment of the text in a radio button.

    Visible Retrieves or sets the value indicating whether the radio button is displayed ornot.

    Table 2.2 lists the important methods of the RadioButton class:

    Table 2.2: Showing the Noteworthy Methods of the RadioButton Class

    Method Description

    PerformClick() Generates a Click event when a user clicks a radio button

    Show() Displays the radio button to the user

    Table 2.3 lists the notable events of the RadioButton class:

    Table 2.3: Showing the Noteworthy Events of the RadioButton Class

    Event Description

    AppearanceChanged Occurs when the value of the Appearance property changes

    CheckedChanged Occurs when the value of the Checked property changes

    Click Occurs when the user clicks the associated radio button

    The CheckBox ControlA CheckBox control is represented as a box shaped control that enables the user to select or deselect an option.This control accepts either true or false as a value. You click a check box to select it and click it again to

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    4/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    34

    deselect it. When you select the check box, it holds the value true; and it holds the value false when youdeselect it.

    Although a check box is usually selected or cleared, this control also has a third indeterminate state. When the

    check box is in the indeterminate state, it is grayed-out. Applications use this state only when partial orunknown selection needs to be represented. Consider an example, where a single check box is used to changethe font style of the text box to bold, italics, or a combination of both. Now, if the text is in either bold or italics,you can easily determine using the check box. However, when the text is both in italics and bold, it becomesdifficult to specify the current state of the check box. This state is known as the indeterminate state. To enableindeterminate state, set the ThreeState property of the check box to true. Figure 2.2 shows check boxes asthey appear at design time:

    Figure 2.2: Displays Check Boxes at Design Time

    The check boxes are based on the CheckBox class. Following is the class hierarchy of the CheckBox class:

    System.ObjectSystem.MarshalByRefObject

    System.ComponentModel.ComponentSystem.Windows.Forms.Control

    System.Windows.Forms.ButtonBaseSystem.Windows.Forms.CheckBox

    Table 2.4 lists the notable properties of the CheckBox class:

    Table 2.4: Showing the Noteworthy Properties of the CheckBox Class

    Property Description

    Appearance Retrieves or sets the appearance of a check box

    AutoCheck Specifies whether or not the Checked or CheckState values and theappearance of the check box should be automatically changed when the checkbox is clicked

    CheckAlign Retrieves or sets the horizontal and vertical alignment of a check box in a control

    Checked Retrieves or sets a value indicating whether or not the check box is in thechecked state

    CheckState Retrieves or sets the state of a check box

    Text Retrieves or sets the caption for the check box

    TextAlignRetrieves or sets the alignment of the caption on the check box

    ThreeState Specifies whether or not the check box should allow three check states, ratherthan two

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    5/36

    In Depth

    35

    Table 2.5 lists the notable events of the CheckBox class:

    Table 2.5: Showing the Noteworthy Events of the CheckBox Class

    Event Description

    AppearanceChanged Occurs when the Appearance property changes

    CheckedChanged Occurs when the value of the Checked property changes

    CheckStateChanged Occurs when the value of the CheckState property changes

    Click Occurs when the user selects the check box

    A CheckBox control can display image, corresponding text associated with the check box, or bothsimultaneously. Use the ImageAlign and TextAlign properties to determine the location where the captionand picture should appear in the CheckBox control.

    You can also use the ImageList and ImageIndex properties of the check box to display an image on the checkbox. Lets now explore the ListBox control.

    The ListBox Control

    A ListBox control displays a list of items from which the user can select one or more item. Figure 2.3 shows listboxes as they appear at design time:

    Figure 2.3: Showing the Design View of the ListBox Control

    If the items exceed a specified limit, a scroll bar automatically appears to let the user to scroll through the list.You can also scroll list boxes horizontally by setting the MultiColumn property to true. In addition, when the

    ScrollAlwaysVisibleproperty is set to true, a scroll bar always appears.

    Following is the class hierarchy for the ListBox class:

    System.ObjectSystem.MarshalByRefObject

    System.ComponentModel.ComponentSystem.Windows.Forms.Control

    System.Windows.Forms.ListControlSystem.Windows.Forms.ListBox

    As you can see in the class hierarchy, the list boxes are derived from the Control class, but not directlyinstead, they are derived directly from the ListControl class.

    Table 2.6 lists the notable properties of the ListBox class:

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    6/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    36

    Table 2.6: Showing the Noteworthy Properties of the ListBox Class

    Property Description

    BorderStyle Retrieves or sets the type of border that is drawn around the list box.

    ColumnWidth Retrieves or sets the width of columns in a multicolumn list box.

    HorizontalExtent Retrieves or sets the horizontal scrolling area of a list box.

    HorizontalScrollbar Retrieves or sets the value indicating whether or not a horizontal scroll barshould be displayed in a list box.

    ItemHeight Retrieves or sets the height of an item in a list box.

    Items Returns a list of items of the list box.

    MultiColumn Retrieves or sets a value indicating whether or not the list box supportsmultiple columns.

    ScrollAlwaysVisible Retrieves or sets a value indicating whether or not a vertical scroll bar shouldalways be displayed.

    SelectedIndex Retrieves or sets the index of the currently selected item of the list box.

    SelectedIndices Retrieves and displays a collection that contains the indices of all the selecteditems in the list box.

    SelectedItem Retrieves or sets the selected item in the list box.

    SelectedItems Retrieves and displays a collection containing the selected items of the list box.

    SelectionMode Retrieves or sets the method in which items are selected. This property enablesyou to determine how many items a user can select at a time and how the usercan make multiple selections.

    Sorted Retrieves or sets a value indicating whether or not the items in the list box are

    sorted. If you set this property to true, the items are sorted alphabetically.

    Text Retrieves the text of the selected item in the list box.

    TopIndex Retrieves or sets the index of the first item of the list box.

    Table 2.7 lists the noteworthy methods of the ListBox class:

    Table 2.7: Showing the Noteworthy Methods of the ListBox Class

    Method Description

    ClearSelected() Deselects all the items in a list box

    FindString() Finds the first item in the list box that begins with the indicated string

    FindStringExact() Finds the first item in the list box that exactly matches the indicated string

    GetSelected() Returns true if the indicated item is selected

    SetSelected() Selects or deselects the indicated item in a list box

    Table 2.8 lists the notable events of the ListBox class:

    Table 2.8: Showing the Noteworthy Events of the ListBox Class

    Event DescriptionClick Occurs when the list box is clicked

    SelectedIndexChanged Occurs when the SelectedIndex property has changed

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    7/36

    In Depth

    37

    The items in list boxes are stored in the Items collection. The Items.Count property holds the number ofitems in the list (the value of the Items.Count property is always one more than the largest possibleSelectedIndex value because selected index is zero-based, i.e., the selected index always starts withzero index).

    To add or delete items in a ListBox control, you can use the Items.Add, Items.Insert, Items.Clear,Items.Remove, or Items.RemoveAt() method. You can also add a number of items to a list boxsimultaneously with the AddRange() method. In addition, you can add and remove items to the list by usingthe Items property at design time.

    You can also support multiple selections in list boxes. The SelectionModeproperty determines the number ofitems that can be selected at a time and can hold one of the following values:

    MultiExtendedSpecifies that multiple items can be selected and the user can use the SHIFT, CTRL, andarrow keys to make selections

    MultiSimpleSpecifies that multiple items can be selected

    NoneSpecifies that no items can be selected

    OneSpecifies that only one item can be selected

    When you support multiple selections, you can use the Items property to access the items in the list box, theSelectedItems property to access the selected items, and the SelectedIndices property to access theselected indices.

    The CheckedListBox ControlSimilar to the ListBox control, the CheckedListBox control also displays a list of items. However, aCheckedListBox control also displays a check box to the left of individual items. This allows you to scrollthrough the list of items and select them by checking the respective check boxes. You can see theCheckedListBox control, as shown in Figure 2.4:

    Figure 2.4: The CheckedListBox Control at Design Time

    Following is the inheritance hierarchy of the CheckedListBox class:

    System.ObjectSystem.MarshalByRefObject

    System.ComponentModel.ComponentSystem.Windows.Forms.Control

    System.Windows.Forms.ListControl

    System.Windows.Forms.ListBoxSystem.Windows.Forms.CheckedListBox

    Similar to other controls, the CheckedListBox control has several properties, methods, and events. Theseproperties, methods, and events can be accessed and customized (optionally) as per the requirements of yourapplication.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    8/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    38

    Table 2.9 lists the noteworthy properties of the CheckedListBox class:

    Table 2.9: Showing the Noteworthy Properties of the CheckedListBox Class

    Property Description

    CheckedItems Holds the collection of checked items in this checked list box

    CheckOnClick Retrieves or sets a value indicating if the check box should be toggled whenthe corresponding item is selected

    ItemHeight Returns the height of an item

    Items Returns a collection of items in a checked list box

    MultiColumn Retrieves or sets a value indicating if the checked list box allows multiplecolumns

    SelectedIndex Retrieves or sets the index of the selected item in a checked list box

    SelectedIndices Retrieves a collection that contains zero-based indices of all currently selecteditems in the checked list box

    SelectedItem Retrieves or sets the selected item in the checked list box

    SelectedItems Retrieves a collection containing the selected items in the checked list box

    SelectionMode Retrieves or sets the current selection mode

    Sorted Retrieves or sets a value indicating if the items in the checked list box shouldbe sorted alphabetically

    Text Retrieves the text of the selected item in a checked list box

    Table 2.10 lists the noteworthy methods of the CheckedListBox class:

    Table 2.10: Showing the Noteworthy Methods of the CheckedListBox Class

    Method Description

    FindString() Finds the first item, which begins with the indicated string, in the checked listbox

    FindStringExact() Finds the first item in the checked list box that exactly matches the indicated

    string

    GetItemChecked() Retrieves a value indicating if the specified item is checked or not

    GetItemCheckState() Retrieves the check state of the current item

    GetSelected() Retrieves a value indicating if the specified item is selected

    SetItemChecked() Checks the item at the specified index

    SetItemCheckState() Retrieves the specified check state of the item

    SetSelected() Selects or clears the selection for the specified item in a checked list box

    Table 2.11 lists the noteworthy events of the CheckedListBox class:

    Table 2.11: Showing the Noteworthy Events of the CheckedListBox Class

    Event Description

    Click Occurs when the user selects the checked list box

    ItemCheck Occurs when the checked state of an item changes

    SelectedIndexChanged Occurs when the SelectedIndex property has changed

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    9/36

    In Depth

    39

    Similar to standard list boxes, you can access the items in a checked list box using the Items property. To checkan item, the user has to double-click a check box by default, unless you set the CheckOnClick property totrue, in which case the user just needs to perform a single click on the check box to select it.

    You can get the checked items in a checked list box with theCheckedItems

    andCheckedIndices

    properties.You can also use the GetItemChecked()method to verify whether or not an item is checked. In addition, youcan use the ItemCheck event to handle check events, and the SetItemChecked()method to check or uncheckitems.

    Checked list boxes can also support three states by using the CheckState enumerationChecked,

    Indeterminate, and Unchecked. You must set the state of Indeterminate in the code because the userinterface does not provide a way of doing so. To use three-state check boxes, you can use theGetItemCheckState and SetItemCheckState() methods instead of the GetItemChecked andSetItemChecked()methods.

    The ComboBox ControlThe ComboBox control is used to display data in a drop-down combo box. The combo box is made up of twoparts. The top part is a text box that allows the user to type in all or part of a list item. The other part is a list boxthat displays a list of items from which the user can select one or more items. In other words, a combo box allows

    the user to either select an item from the list or enter the data through the keyboard. Figure 2.5 shows theComboBox control as it appears at design time:

    Figure 2.5: Showing the Design View of the ComboBox Control

    Following is the inheritance hierarchy of the ComboBox class:

    System.ObjectSystem.MarshalByRefObject

    System.ComponentModel.ComponentSystem.Windows.Forms.Control

    System.Windows.Forms.ListControlSystem.Windows.Forms.ComboBox

    As you can see in the inheritance hierarchy, the ComboBox class is derived from the ListControl class, similarto the ListBox class.

    Table 2.12 lists the notable properties of the ComboBox class:

    Table 2.12: Showing the Noteworthy Properties of the ComboBox Class

    Property Description

    AutoCompleteCustomSource Retrieves or sets a custom StringCollection class to use when the

    AutoCompleteSource property is set to CustomSource. This propertyhelps in incorporating auto-complete feature in combo box.

    AutoCompleteMode Retrieves or sets an option that controls the automatic completion for thecombo box.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    10/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    40

    Table 2.12: Showing the Noteworthy Properties of the ComboBox Class

    Property Description

    AutoCompleteSource Retrieves or sets a value indicating the source of complete strings used for

    automatic completion.

    DataSource Retrieves or sets the data source for the combo box.

    DropDownHeight Retrieves or sets the height in pixels for the drop-down portion of the combobox.

    DropDownStyle Retrieves or sets the style of the combo box.

    DropDownWidth Retrieves or sets the width of the drop-down part of the combo box.

    DroppedDown Retrieves or sets a value indicating whether the combo box is displaying itsdrop-down part.

    FlatStyle Retrieves or sets the appearance of the combo box.

    Focused Retrieves a value specifying if the combo box has the focus.

    ItemHeight Retrieves or sets the height of an item in a combo box.

    Items Retrieves a collection of the items in the combo box.

    MaxDropDownItems Retrieves or sets the maximum number of items to be shown in the drop-downpart of a combo box.

    MaxLength Retrieves or sets the maximum number of characters a user can enter in thetext box of the combo box.

    SelectedIndex Retrieves or sets the index of the currently selected item.

    SelectedItem Retrieves or sets currently selected item in the combo box.

    SelectedText Retrieves or sets the selected text in the text box part of a combo box.

    SelectionLength Retrieves or sets the number of characters selected in the text box part of thecombo box.

    SelectionStart Retrieves or sets the starting index of selected text in the combo box.

    Sorted Retrieves or sets a value indicating if the items in the combo box are sorted.

    Text Retrieves or sets the text associated with the combo box.

    Table 2.13 lists the noteworthy methods of the ComboBox class:

    Table 2.13: Showing the Noteworthy Methods of the ComboBox Class

    Method Description

    FindString() Finds the first item in the combo box that begins with the specified string

    FindStringExact() Finds the item that matches the specified string exactly

    Select() Selects a range of text

    SelectAll() Selects all the text in the text box of the combo box

    Table 2.14 lists the noteworthy events of the ComboBox class:

    Table 2.14: Showing the Noteworthy Events of the ComboBox Class

    Event Description

    DropDown Occurs when the drop-down portion of a combo box is shown

    DropDownClosed Occurs when the drop-down portion of the combo box is no longer visible

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    11/36

    In Depth

    41

    Table 2.14: Showing the Noteworthy Events of the ComboBox Class

    Event Description

    DropDownStyleChanged Occurs when the DropDownStyle property has changed

    SelectedIndexChanged Occurs when the SelectedIndex property has changed

    SelectionChangeCommitted Occurs when the selected item has changed and that change also appears inthe combo box

    TextUpdate Occurs when the combo box has formatted the text, but prior to theappearance of the text

    You can use the Text property of a combo box to set and access the text in the text box of the combo box. Youcan use the SelectedIndexproperty to get the selected list item. You can change the selected item by changingthe SelectedIndex value in the code, which displays the corresponding item in the text box portion of thecombo box. As with list boxes, if no items are selected, the SelectedIndex value is set to -1. If the first item inthe list is selected, the SelectedIndexvalue is set to 0.

    In addition, you can also use the SelectedItemproperty, which is similar to the SelectedIndex property,but returns the item selected (often a string value). The Items.Count property reflects the number of items in

    the list (the value of the Items.Count property is always one more than the largest possible SelectedIndexvalue because SelectedIndex is zero-based).

    To add or delete items in a ComboBox control, use the Items.Add, Items.Insert, Items.Clear,

    Items.AddRange, Items.Remove, or Items.RemoveAt()method. Alternatively, you can add and removeitems from the list by using the Items property at design time.

    By default, a combo box displays a text box with a hidden drop-down list. The DropDownStyle propertydetermines the style of the combo box to be displayed. You can set this property to display the list box of thecombo box in the following combo box styles:

    DropDownSpecifies that the text portion is not editable and you must use an arrow to see the drop-downlist box. It is the default drop-down style.

    DropDownListSpecifies that the text portion is editable and the user can use the arrow key to view thelist.

    SimpleSpecifies that the list is always displayed.

    To display a list that the user cannot edit, you should use a list box instead of a combo box.

    You can add and remove items in combo boxes in the same ways as you can with list boxes. You can also use theBeginUpdate() and EndUpdate() methods to add a large number of items to the combo box withoutredrawing the control each time an item is added to the list. The FindString() and FindStringExact()methods let you search for an item in the list that contains a particular search string. Similar to list boxes, you usethe SelectedIndex property to get or set the index of the currently selected item, and the SelectedItemproperty to get or set the selected item. You can also use the Text property to specify the string displayed in thetext box part of the combo box.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    12/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    42

    Immediate Solutions

    Using the RadioButton ControlAs mentioned in the In Depth section, a RadioButton control allows a user to select one item from an exclusivegroup of items. Let us see some of its properties in action by creating an application, namedRadioButtonSample (available in the CD-ROM). This example contains a sample user interface form withthree radio buttons; Left, Center, and Right, and one button control. When you select any of these radio buttons,the button control on the form aligns itself as per the selected radio button option. If you click the button, amessage box displays a message indicating the selected radio button and at the same time, all the radio buttonsare transformed to toggle buttons.

    To create this application, you need to perform the following broad-level steps:

    1. Setting the text for the RadioButton controls

    2. Retrieving and setting the check state of the RadioButton controls

    3. Creating toggle buttons

    Lets explore these in detail next.

    Setting the Text for the RadioButton ControlsYou can set the text for the RadioButton controls in two ways at design time and at run time. While in thedesign mode, you can set the Text property for a radio button by first selecting the radio button and setting its

    Text property in the Properties window. This example; however, explains how to set the text of the radiobuttons at run time. To do so, perform the following steps in the RadioButtonSampleapplication:

    1. Set the Text property of the Form1 form to Radio Button Sample.

    2. Drag and drop a Button control and three RadioButton controls to the form and change the Textproperty of the Button control to Click Me.

    3. Add the code, shown in Listing 2.1, on the Load event of the form to set the Text property of the radiobuttons at run time:

    Listing 2.1: Showing the Code for the Load Event of the Formprivate void Form1_Load(object sender, EventArgs e){

    radioButton1.Text = "Left";radioButton2.Text = "Center";radioButton3.Text = "Right";

    }

    4. Change the Bold property of all the radio buttons to true and change the Text property of the button toClick Me.

    5. Press the F5 key on the keyboard to execute the application and the output of the application appears, asshown in Figure 2.6:

    Figure 2.6: Displays the Text Set for the Radio Buttons

    Retrieving and Setting the Check State of the RadioButton ControlsYou can check whether or not a radio button is selected by using the Checked property. This property of theradio button has only two settings, true if the button is selected and false if not selected.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    13/36

    Immediate Solutions

    43

    Lets use the same application, RadioButtonSample, to demonstrate whether or not a radio button is selected.To do so, perform the following steps:

    1. Double-click the Click Me button in the design mode of the Form1.cs file to generate its Click event and add

    the code, as shown in Listing 2.2:Listing 2.2: Showing the Code for Retrieving the Check State of Radio Buttons

    private void button1_Click(object sender, EventArgs e){

    if (radioButton1.Checked == true) {MessageBox.Show("The Radio Button Left is selected.");

    }if (radioButton2.Checked == true) {

    MessageBox.Show("The Radio Button Center is selected.");}if (radioButton3.Checked == true){

    MessageBox.Show("The Radio Button Right is selected.");}

    }

    2. Press the F5 key on the keyboard to execute the application. When the form appears, observe that bydefault the first radio button is selected.

    3. Click the Click Me button, a message box appears showing that the Left radio button is selected, as shownin Figure 2.7:

    Figure 2.7: Showing a Message Box on Selection of Left Radio Button

    Similarly, you can also determine whether or not, a radio button should be selected, by performing the followingsteps:

    4. Add the highlighted code, shown in Listing 2.3, in the Load event of the form:

    Listing 2.3: Showing the Code for Setting the Check State of Radio Buttons

    private void Form1_Load(object sender, EventArgs e){

    radioButton1.Text = "Left";radioButton2.Text = "Center";radioButton3.Text = "Right";radioButton2.Checked = true;

    }

    5. Press the F5 key on the keyboard to execute the application and the output appears, as shown in Figure 2.8:

    Figure 2.8: Displays a Radio Button Selected

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    14/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    44

    Creating Toggle ButtonsYou can turn check boxes or radio buttons into toggle buttons if you set their Appearance property to Button(by default, the value of the Appearance property is Normal). Toggle buttons resemble standard buttons but

    act similar to the check boxes or radio buttons. Lets perform the following steps to transform radio buttons intotoggle buttons:

    1. Add the highlighted code, shown in Listing 2.4, in the Click event of the button (i.e., to transform the radiobuttons to toggle buttons):

    Listing 2.4: Showing the Code for Creating the Toggle Buttons

    private void button1_Click(object sender, EventArgs e){

    if (radioButton1.Checked == true){

    MessageBox.Show("The Radio Button Left is selected.");}if (radioButton2.Checked == true){

    MessageBox.Show("The Radio Button Center is selected.");}if (radioButton3.Checked == true)

    { MessageBox.Show("The Radio Button Right is selected.");}

    radioButton1.Appearance = Appearance.Button;radioButton2.Appearance = Appearance.Button;radioButton3.Appearance = Appearance.Button;

    }

    2. Add the code, shown in Listing 2.5, to the CheckedChanged event of the radio buttons to align the buttonleft, center, or right, as per the radio button selected:

    Listing 2.5: Showing the Code for Aligning the Button on the Selection of a Radio Button

    private void radioButton1_CheckedChanged(object sender, EventArgs e){

    button1.Location = new System.Drawing.Point(50, 100);}private void radioButton2_CheckedChanged(object sender, EventArgs e){

    button1.Location = new System.Drawing.Point(160, 100);}private void radioButton3_CheckedChanged(object sender, EventArgs e){

    button1.Location = new System.Drawing.Point(250, 100);}

    3. Press the F5 key on the keyboard to execute the application, when the form appears, select the Right radiobutton. Observe that the button aligns to the right of the form, as shown in Figure 2.9:

    Figure 2.9: Changing the Alignment of the Button to the Right

    4. Click the Click Me button, all the radio buttons are transformed to the toggle buttons, as shown inFigure 2.10:

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    15/36

    Immediate Solutions

    45

    Figure 2.10: Radio Buttons Transformed to Toggle Buttons

    Till now, you have learned some of the most common tasks that we normally perform with radio buttons. Letsnow shift our focus to the CheckBox control.

    Using the CheckBox ControlYou are already familiar with the properties of the CheckBox control. To see how these properties work, let uscreate an application named CheckBoxSample (available in the CD-ROM). This application displays the totalnumber of words and characters entered in a text box. To do so, this application uses a TextBox control, aButton control, a Label control, and three CheckBox controls. The functions of each of these CheckBoxcontrols are as follows:

    The first one enables the counting of the number of characters entered in the textbox The second one enables the words count

    The last one is set to an indeterminate state

    The last check box determines the state on the basis of the selections made in the first two check boxes. If the firstand the second check boxes are not selected, the third one also remains clear; if the first two check boxes areselected, the third one also gets selected. However, if one of these is checked and the other is clear, the thirdcheck box shows an indeterminate state. Finally, a label displays the total number of characters and wordsentered in the text box.

    To create this application, perform the following broad-level steps:

    1. Set the text for the CheckBox controls

    2. Retrieve and set the check state of the CheckBox controls

    3. Create three-stateCheckBox controls

    Lets explore these in detail next.

    Setting the Text for the CheckBox ControlsSimilar to any other Windows Forms controls, you can set the text for the check box using the Text property. Todo so, perform the following steps in the CheckBoxSample application:

    1. Set the Text property of the Form1 form to Check Box Sample.

    2. Drag and drop a TextBox control to the form and set its Multilineproperty to true.

    3. Drag and drop a Button control to the form and set its Text property as Find.

    4. Add three CheckBox controls to the form and add the code on the Load event of the form to set the Textproperty of the CheckBox controls, as shown in Listing 2.6:

    Listing 2.6: Showing the Code for Setting the Text Property of the CheckBox Controlprivate void Form1_Load(object sender, EventArgs e){

    checkBox1.Text = "Chars count";checkBox2.Text = "Words count";

    checkBox3.Text = "Check box displaying indeterminate state";}

    5. Add a Label control and change the Text property of the Label control to blank.

    6. Disable the CheckBox3 control by setting its Enabled property to false.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    16/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    46

    7. Press the F5 key on the keyboard to execute the application. The output of the application appears, asshown in Figure 2.11:

    Figure 2.11: Displays the Text Set for the Check Boxes

    Retrieving and Setting the Check State of the CheckBox ControlsYou can see if a check box is checked by examining its Checked property. This property can be set to eithertrue or false. Similarly, the same property is used to set the state of the check box to true or false.

    Let us use the same application, CheckBoxSample, to show if a check box is selected or not. To do so, performthe following steps:

    1. Double-click the Find button in the design mode of the Form1.cs file and add the code, given in Listing 2.7,in the Code Editor:

    Listing 2.7: Showing the Code for Retrieving the Check State of CheckBoxControls

    private void button1_Click(object sender, EventArgs e){

    if (checkBox1.Checked == true && checkBox2.Checked == true){

    checkBox3.Checked = true;}

    if (checkBox1.Checked == false && checkBox2.Checked == false){

    checkBox3.Checked = false;}

    }

    2. Add the highlighted code to set the check state of the check box in the Load event of the form, as shown inListing 2.8:

    Listing 2.8: Showing the Code for Setting the Check State of the Check Box

    private void Form1_Load(object sender, EventArgs e){

    checkBox1.Text = "Chars count";checkBox2.Text = "Words count";checkBox3.Text = "Check box displaying indeterminate state";

    checkBox1.Checked = true;textBox1.Text = "Welcome to Visual C# 2010";label1.Text = "Total characters : " + textBox1.TextLength;checkBox3.CheckState = CheckState.Indeterminate;

    }

    3. Press the F5 key on the keyboard to execute the application and the output is displayed, as shown inFigure 2.12:

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    17/36

    Immediate Solutions

    47

    Figure 2.12: Showing the Selected Check Box

    Creating Three-State CheckBox Controls

    As stated earlier, a check box typically displays two states Checked and Unchecked. However, to display theindeterminate state, the ThreeState property of the CheckBox control should be set to true and the

    CheckState property should be set to CheckState.Indeterminateat design time or run time.

    Let us perform the following steps to create three-state CheckBox controls:

    1. Add the highlighted code, shown in Listing 2.9, to set the indeterminate state of CheckBox3 at the Clickevent of the button:

    Listing 2.9: Showing the Code for Setting the Indeterminate State for CheckBox3

    private void button1_Click(object sender, EventArgs e){

    if (checkBox1.Checked == true && checkBox2.Checked == true){

    checkBox3.Checked = true;}if (checkBox1.Checked == false && checkBox2.Checked == false){

    checkBox3.Checked = false;

    }if ((checkBox1.Checked == false && checkBox2.Checked == true) || (checkBox1.Checked ==

    true && checkBox2.Checked == false)){

    checkBox3.CheckState = CheckState.Indeterminate;}

    }

    2. Add the highlighted code, shown in Listing 2.10, on the Click event of the button for displaying the totalnumber of characters and words entered in the text box:

    Listing 2.10: Showing the Code to Display the Total Number of Characters and Words

    private void button1_Click(object sender, EventArgs e){

    int wrdcount = 0;int chrcount = 0;label1.Text = "";checkBox3.Checked = false;if (checkBox1.Checked == true){

    chrcount = textBox1.Text.Length;label1.Text = "Total characters : " + chrcount;

    }

    if (checkBox2.Checked == true)

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    18/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    48

    {if (textBox1.Text.Trim().Length == 0){

    label1.Text = label1.Text + " " + "Total words : 0";}

    else{

    string[] str = textBox1.Text.Split(' ');wrdcount = str.Length;label1.Text = label1.Text + " " + "Total words : " + wrdcount;

    }}

    if (checkBox1.Checked == true && checkBox2.Checked == true){

    checkBox3.Checked = true;}if (checkBox1.Checked == false && checkBox2.Checked == false){

    checkBox3.Checked = false;}if ((checkBox1.Checked == false && checkBox2.Checked == true) || (checkBox1.Checked ==

    true && checkBox2.Checked == false))

    {checkBox3.CheckState = CheckState.Indeterminate;

    }}

    In Listing 2.10, you can see that the total number of characters are calculated using the Length property of thetext box. However, for counting the total number of words, we first apply a condition to verify whether the userhas entered any text in the text box. If no text has been entered, the total characters and total words are set tozero. If the text box has some text, the function counts the words separated by a space using the Split()method, and stores the resulting words in a String array. Later, the length of the array is stored in the

    wrdcount variable, which contains the number of words entered in the text box.

    3. Press the F5 key on the keyboard to run the application; you can see the result as shown in Figure 2.13:

    Figure 2.13: Displaying the Indeterminate State of the Check Box

    As you can see in Figure 2.13, the Chars count check box is selected and displays the total number of characters

    entered in the text box. In addition, also notice that the last check box displays an indeterminate state. Now,select the Words count check box and click the Find button, as shown in Figure 2.14:

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    19/36

    Immediate Solutions

    49

    Figure 2.14: Displaying the Total Characters and Words in the Text Box

    Now, you might be quite clear with the similarities and differences between the RadioButton and CheckBoxcontrols. Let us now see how to use the ListBox control.

    Using the ListBox ControlUsing a list box, you can perform a number of actions, such as adding items to the list box, retrieving the numberof items, sorting the items, and working with a selected item. Let us see each of these in detail by first creating anapplication called ListBoxSample (available in the CD-ROM). This application contains two ListBoxcontrols, five Button controls, a TextBox control, and a blank Label control on the Form1 form. Now, set theText property of the Button controls used in the application, as shown in Table 2.15:

    Table 2.15: Showing the Text Property of the Button Controls

    Text Property Description

    Fill list box Fills the first list box with some items

    Get indexes Retrieves the indexes of all the items in the first list box and displays those indexes in thesecond list box

    Sort items Sorts the items in the first list box

    Remove items Removes a particular item from the first list box

    Clear list box Clears the first list box

    Finally, a text box displays the selected item in a list box and a label displays the total number of items in the listbox.

    To create this application, perform the following broad-level steps:

    1. Add items to the ListBox controls

    2. Retrieve the index of items of the ListBox controls

    3. Retrieve the number of items in the ListBox controls

    4. Sort items in the ListBox controls

    5. Retrieve the selected item of the ListBox controls

    6. Create ListBox controls with multiple columns

    7. Create multiselect list boxes

    8. Handle the SelectedIndexChangedevent9. Remove items from the ListBox controls

    Lets understand these in detail next.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    20/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    50

    Adding Items to the ListBox ControlsYou can add items to a list box at either design time or run time. The first item in the list box has index 0, thenext index 1, and so on. At design time, you can use the Items property, which stores array of items in the list

    box, and at run time, you can use both the Items property and the Add()method.How do you keep track of the total number of items in a list box? You can use the Items.Countproperty, i.e., ifyou loop over the items in the control, use the Items.Count property as the maximum value to loop to. Youcan access items individually in a list box by index using the Items property, as shown the following codesnippet:

    strText = listBox1.Items[5].ToString ();

    At design time, you can add items directly to your list box by typing them into the Items property in theProperties window. Selecting the Items property displays the String Collection Editor dialog box, and you cantype item after item into the list box, as shown in Figure 2.15:

    Figure 2.15: Adding Items to a List Box

    At run time, you can use the Add() or Insert()method of the Items property to add items to the list box.

    Perform the following steps to add items to a list box:

    1. Double-click the Fill list box button in the design mode of the Form1.cs file and add the code shown inListing 2.11:

    Listing 2.11: Showing the Code to Add the Items to the List Box

    private void button1_Click(object sender, EventArgs e){

    int intLoopIndex = 0;for (intLoopIndex = 1; intLoopIndex

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    21/36

    Immediate Solutions

    51

    Note that when you add items in a list box, they are stored by index. If you are required to add an item at aspecified index, suppose at the middle of an already existing items list, you need to have two pieces ofinformation the item to be added and its index number. In such a case, you use the Insert() method foradding items at a specified index, as shown in the following code snippet:

    listBox1.Items.Insert (3, "Item 3") ;

    In this way, using the Insert() method, you can insert an item anywhere in between the list box.

    Retrieving the Index of Items of the ListBox ControlsYou can retrieve the index of items added in a list box, especially when you require inserting an item in betweenthe list box at a specified index.

    Now, lets learn how to retrieve the indexes of the items in a list box. To do so, double-click the Get indexesbutton in the design mode of the Form1.cs file and add the code, shown in Listing 2.12, on the Click event of theGet indexes button:

    Listing 2.12: Showing the Code to Retrieve the Indexes of all the Items in a List Box

    private void button2_Click(object sender, EventArgs e){

    int intLoopIndex = 0;for (intLoopIndex = 0; intLoopIndex < listBox1.Items.Count; intLoopIndex++)

    { listBox2.Items.Add("Index " + intLoopIndex.ToString());}

    }

    In Listing 2.12, notice that loop variable intLoopIndex has been initialized a value of 0. This is because anindex of an item always starts with 0. In addition, also observe that the loop terminates at a number less than thetotal items in the list box.

    Press the F5 key on the keyboard to execute the application, when the form appears, click the Fill list box buttonand then click the Get indexes button. You can see the output, as shown in Figure 2.17:

    Figure 2.17: Retrieving all Item Indexes

    Now using the indexes, you can very easily insert an item in between the list box.

    Retrieving the Number of Items in the ListBox ControlsThe Count() method is used to retrieve the total number of items in the list box. This is required in situationswhere you need to iterate through the items till the last item in the list.

    Lets learn about retrieving the total number of items in a list box. To do so, double-click the Get indexes buttonin the design mode of the Form1.cs file and add the highlighted code at the Click event of the Get indexesbutton, as shown in Listing 2.13:

    Listing 2.13: Showing the Code to Count the Total Number of Items of List Box

    private void button2_Click(object sender, EventArgs e){

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    22/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    52

    int intLoopIndex = 0;for (intLoopIndex = 0; intLoopIndex < listBox1.Items.Count; intLoopIndex++){

    listBox2.Items.Add("Index " + intLoopIndex.ToString());}

    label1.Text = "Total number of items : " + listBox1.Items.Count;}

    Press the F5 key on the keyboard to execute the code. When the form appears, click the Fill list box button andthen click the Get indexes button. You can see the result, as shown in Figure 2.18:

    Figure 2.18: Showing the Total Number of Items

    Let us now see how sorting of items in a list box is performed.

    Sorting Items in the ListBox ControlsYou can sort the items in a list box alphabetically by setting its Sorted property to true (it is false by default)at design time or run time.

    To sort items in a list box, double-click the Sort items button in the design mode of the Form1.cs file and add thecode on the Click event of the button, as shown in Listing 2.14:

    Listing 2.14: Showing the Code for the Sorting the Items

    private void button3_Click(object sender, EventArgs e){

    listBox1.Sorted = true;}

    Press theF5

    key on the keyboard to execute the application. When the form appears, click the Fill list box button,Get indexes button, and Sort items button. You can see the result, as shown in Figure 2.19:

    Figure 2.19: Displaying Sorted List

    You should know; however, that sorting a list box can change the indices of the items in that list box (unless they were alreadyin alphabetical order). After the sorting is completed, the first item in the newly sorted list has index 0, the next index 1, and so

    on.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    23/36

    Immediate Solutions

    53

    Retrieving the Selected Item of the ListBox ControlsIf a list box supports only single selection, you can use the SelectedIndex property to get the index of theselected item, and the SelectedItemproperty to get the selected item in a list box.

    Listing 2.15 shows how we can display a selected item with its index at the Click event of the list box:Listing 2.15: Showing the Code to Display the Selected Items

    private void listBox1_Click(object sender, EventArgs e){

    textBox1.Text = "The selected item : " + listBox1.SelectedItem.ToString() + " has anindex : " + listBox1.SelectedIndex;

    }

    Press the F5 key on the keyboard to run the application. When the form appears, click the Fill list box button, Getindexes button, and finally select an item from the first list box. You can see the result, as shown in Figure 2.20:

    Figure 2.20: Displaying the Selected Item and its Index

    ListBox controls support multiple selections if you set their SelectionMode property to either MultiSimple or MultiExtended. Usethe SelectedItems and SelectedIndices properties of the list box to make them multi-select. You can refer to the Creating

    Multiselect List Boxes section of this chapter for more information about selecting the multiple items in the ListBox control.

    Creating ListBox Controls with Multiple ColumnsYou can display the items in the list box in multiple columns by setting its MultiColumn property to true.

    Now, on the Load event of the Form1 form, add the code, as shown in the following code snippet:listBox1.MultiColumn = true;

    Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill list box buttonand the Get indexes button. The output is displayed, as shown in Figure 2.21:

    Figure 2.21: Displaying Multi-column List Box

    Creating Multiselect List BoxesYou need to set the SelectionMode property of the list box to MultiExtended to make the list box a multi-select list box. Following are the possible values to be set in the SelectionModeproperty:

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    24/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    54

    MultiExtendedEnables selection of multiple items, and the user can use the SHIFT, CTRL, and arrowkeys to make selections

    MultiSimpleEnables selection of multiple items

    NonePrevents you to select items OneEnables selection of only one item

    To enable multiple selection, add the following code snippet on the Load event of the Form1 form:

    private void Form1_Load(object sender, EventArgs e){

    listBox1.MultiColumn = true;listBox1.SelectionMode = SelectionMode.MultiExtended;

    }

    To indicate how multiple selections look, we also use the SetSelected() method of the list box, which youcan use to set some items in the list box selected. The code for selecting the items of a list box at runtime ishighlighted in Listing 2.16:

    Listing 2.16: Showing the Code for Selecting Multiple Items in the List Box

    private void button1_Click(object sender, EventArgs e){

    int intLoopIndex = 0;for (intLoopIndex = 1; intLoopIndex 1){

    textBox1.Text = "";

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    25/36

    Immediate Solutions

    55

    textBox1.Text = "Selected items: ";foreach (var Item in listBox1.SelectedItems){

    textBox1.Text += Item.ToString() + " ";}

    }}

    Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill list box button,the Get indexes button, and finally click some items in the first list box. You can see that the selected itemsappear in the text box, as shown in Figure 2.23:

    Figure 2.23: Handling List Box Events

    In Figure 2.23, all the selected items in the list box are displayed in the text box.

    Removing Items from the ListBox ControlsYou can remove one item at a time from a list box using either the Remove() or RemoveAt() method. Toremove items from the list box, perform the following steps:

    1. Double-click the Remove items button in the design mode of the Form1.cs file and add the following codesnippet on the Click event of the button:

    listBox1.Items.Remove("Item 6");listBox1.Items.RemoveAt(0);

    In the preceding code snippet, the Remove() method takes the item to be removed as a parameter; whereas, the

    RemoveAt()method takes the index of the item as a parameter.2. Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill list box

    button and then click the Remove items button. The result is, as shown in Figure 2.24:

    Figure 2.24: Removing Selected Items from the List Box

    In Figure 2.24, the Remove items button has removed items Item 1 and Item 6.

    Similarly, you can use the Clear()method of the Items collection to clear a list box.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    26/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    56

    3. Double-click the Clear list box button in the design mode of the Form1.cs file and add the following codesnippet on the Click event of the button control:listBox1.Items.Clear();textBox1.Text = "";

    4. Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill list boxbutton and then the Clear list box button to clear all the items from the list box, as shown in Figure 2.25:

    Figure 2.25: Showing an Empty List Box

    What you have seen are some of the most common properties, methods, and events associated with a list box.Now, let us discuss the CheckedListBox control.

    Using the CheckedListBox ControlAs discussed in the In Depth section of this chapter, checked list boxes support check boxes for each item in a list.In a checked list box, you can add items, set and retrieve the check state of the items, and handle its ItemCheckevent, which you will see in the coming topics.

    Let us explore each of these in detail by first creating an application, named CheckedListBoxSample(available in the CD-ROM). In this application, add a CheckedListBox control, three Button controls, and aTextBox control. Change the Text property of the Button controls toFill items, Uncheck items, and Find checked,respectively.

    To create this application, perform the following broad-level steps:

    1. Add items to the CheckedListBox controls2. Set the check state of items in the CheckedListBox controls

    3. Retrieve the check state of items in the CheckedListBox controls

    4. Handle the ItemCheck event of the CheckedListBox controls

    Lets discuss each of these in detail next.

    Adding Items to the CheckedListBox ControlsYou can add items to the CheckedListBox control similar to the ListBox control. However, you can also passanother argument to the Items.Add()method call at the time of adding the items in the checked list box. Withthis argument, you specify whether the added item is selected by default or not. Now, double-click the Fill itembutton in the design mode of the Form1.cs file and add the code, shown in Listing 2.18, on the Click event of thebutton:

    Listing 2.18: Showing the Code for Adding Items to the Checked List Box

    private void button1_Click(object sender, EventArgs e){checkedListBox1.Items.Clear();checkedListBox1.Items.Add("Mango", true);checkedListBox1.Items.Add("Grapes", true);checkedListBox1.Items.Add("Orange", false);checkedListBox1.Items.Add("Apple", false);

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    27/36

    Immediate Solutions

    57

    checkedListBox1.Items.Add("Banana", true);checkedListBox1.Items.Add("Guava", false);

    }

    Press the F5 key on the keyboard to execute the application. You can see the result of this code by clicking the

    Fill items button, as shown in Figure 2.26:

    Figure 2.26: Showing a Checked List Box

    Let us now see how to set the check state of items in a checked list box.

    Setting the Check State of Items in the CheckedListBox ControlsYou can use the SetItemChecked()method of the checked list box to select or clear items in a checked list boxby passing a value of true or false, respectively. In this example, we are clearing the selection of some of theselected items in the checked list box. To do so, double-click the Uncheck item button in the design mode of theForm1.cs file and add the following code snippet on the Click event of the button for clearing the selecting ofitems:

    checkedListBox1.SetItemChecked(1, false);checkedListBox1.SetItemChecked(4, false);

    Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill Item buttonand then the Uncheck item button. Clicking the Uncheck item button clear the items, as shown in Figure 2.27:

    Figure 2.27: Clearing the Selection of Items in Checked List Box

    Retrieving the Check State of Items in the CheckedListBox ControlsYou can determine whether an item displays a checkmark in a checked list box using the GetItemChecked()method, which returns true if an item is selected. For example, in the CheckedListBoxSampleexample, youcan loop over all items in the checked list box and display the selected items in a text box. To do so, double-clickthe Find checked button in the design mode of the Form1.cs file and add the code on its Click event, as shown inListing 2.19:

    Listing 2.19: Showing the Code for Retrieving the Check State of Items

    private void button3_Click(object sender, EventArgs e){

    int intLoopIndex = 0;string strText = null;strText = "Checked Items: ";

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    28/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    58

    for (intLoopIndex = 0; intLoopIndex

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    29/36

    Immediate Solutions

    59

    textBox1.Text = "Item " + (e.Index + 1) + " is not selected";break;

    }}

    Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill Item buttonand then select an item from the checked list box. You can see the result in Figure 2.29, where we have justchecked Apple in the checked list box, and the same have been shown in the text box:

    Figure 2.29: Showing the Selected Item in the Text Box

    We have set the CheckOnClick property for the CheckedListBoxSample example in this chapter to true (the default setting forthis property is false), so all it takes is one click to generate an ItemCheck event. By default, however, a double-click would beneeded.

    Using the ComboBox ControlAs discussed in the In Depth section of this chapter, combo boxes combine a text box and a list box (which is whythey are called combo boxes). Similar to a list box, you can add items, work with the selected item, retrieve thetotal number of items, and sort items in a combo box. To do so, create an application named ComboBoxSample(available in CD-ROM). In this application, you will find a combo box and four buttons. Set the following text ofthese buttons used in the application, as follows:

    Fill combo boxFills the combo box with items Get selectedGets the items selected in the combo box

    Sort itemsSorts the items in the combo box

    Storing objectsStores objects in the combo box

    Finally, a text box is used to display the selected items in the combo box.

    The following broad-level steps need to be performed to create this application:

    1. Adding items in the ComboBox controls

    2. Setting the drop-down style of the ComboBox controls

    3. Setting the selected item of the ComboBox controls

    4. Retrieving the number of items in the ComboBox controls

    5. Sorting the items in a ComboBox control

    6. Storing objects in the ComboBox controls

    7. Using the AddRange()method8. Handling the TextChanged and SelectedIndexChanged events

    Lets discuss each of these in detail next.

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    30/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    60

    Adding Items in the ComboBox ControlsAs already learned, a combo box is a combination of a text box and a list box, so at design time you can changethe text in the text box part by changing the Text property of the combo box. You can change the items in the

    list box part with the Items property (this item opens the String Collection Editor dialog box discussed for listboxes when you click it in the Properties window) at design time.

    As with list boxes, you can also use the Items.Insert(), Items.Add(), and Items.AddRange()methodsto add items to the list part of a combo box. Now, double-click the Fill combo box button in the design mode ofthe Form1.cs file and add the code, shown in Listing 2.22, on the Click event of the button for adding items in theComboBox control:

    Listing 2.22: Showing the Code for Adding Items in a Combo Box

    private void button1_Click(object sender, EventArgs e){

    comboBox1.Items.Clear();int intLoopIndex = 0;for (intLoopIndex = 0; intLoopIndex

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    31/36

    Immediate Solutions

    61

    the list. Following are the settings for the DropDownStyleproperty of the combo box (these are members of theComboBoxStyle enumeration):

    DropDown (default value)Includes a drop-down list and a text box. The user can select from the list or

    type in the text box. SimpleIncludes a text box and a list, which does not drop down. The user can select from the list or type

    in the text box. The size of a simple combo box includes both the edit and list portions. By default, a simple

    combo box is sized so that none of the list is displayed. Increase the Height property to display more of thelist.

    DropDownListIncludes only drop-down list and the user can only select the existing value from thedrop-down list. This is a good one to keep in mind when you want to restrict the input from the user.

    You can see a Simple dropdown style combo box in Figure 2.31, created by setting the DropDownStyleproperty to Simple in the Properties window of the combo box:

    Figure 2.31: Displaying a Simple Style Combo Box

    The next topic deals with setting the selected items in a combo box.

    Setting the Selected Item of the ComboBox ControlsWhen you make a selection in a combo box, the new selection appears in the text box of the combo box.Therefore, it is easy to get the text of the current selectionyou just use the Text property of the combo box.

    You can also use the SelectedIndex and SelectedItemproperties to get the index of the selected item andits value, respectively. In the ComboBoxSample example, we display the information in about the currentlyselected item in a combo box, when the user clicks the Get selected button. Now, add the code, shown in Listing2.23, on the Click event of the Get selected button:

    Listing 2.23: Showing the Code to Display Selected Item and Selected Index of Combo Box

    private void button2_Click(object sender, EventArgs e){

    if (comboBox1.SelectedIndex > -1){

    int selectedIndex = 0;selectedIndex = comboBox1.SelectedIndex;object selectedItem = null;selectedItem = comboBox1.SelectedItem;textBox1.Text = "Selected item text: " + selectedItem.ToString() + " Selected

    index: " + selectedIndex.ToString();}}

    Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill combo boxbutton and then the Get selected button. The result is displayed, as shown in Figure 2.32:

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    32/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    62

    Figure 2.32: Displaying the Selected Item and Selected Index of the Combo Box in a Text Box

    If you want to restrict the users to insert the item in the combo box or to modify the existing item of the combo box, set theDropDownStyle property of the combo box to DropDownList. In this style of combo boxes, the user cannot type into the textpart of the control.

    Retrieving the Number of Items in the ComboBox ControlsA combo box can contain various items, and counting all the items may consume more time and efforts. Thisproblem can be solved with the help of the Item.Count property of the combo box. The Item.Count propertycounts all the items listed in the combo box and gives you the result. Now, add the highlighted code on the Clickevent of the Fill combo box button, as shown in Listing 2.24:

    Listing 2.24: Displays the Total Number of Items in a Combo Box

    private void button1_Click(object sender, EventArgs e){

    comboBox1.Items.Clear();int intLoopIndex = 0;for (intLoopIndex = 0; intLoopIndex

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    33/36

    Immediate Solutions

    63

    Sorting the Items in a ComboBox ControlThe use of sorting can easily be understood by considering a scenario. Suppose, you have been newlycommissioned to write the guidebook to the zoo with Visual C# and everything looks greatexcept for one

    thing. The program features a combo box with a list of animals that the user can select to learn more about, andit would be great if you could make that list appear in an alphabetical orderbut the zoo keeps adding andtrading animals all the time. Still, it is no problem, because you can leave the work up to the combo box itself ifyou set its Sorted property to true (the default is false).

    For example, we set the Sorted property to true for a combo box, ComboBox1. Now, it does not matter inwhat order you add items to that combo box. To do so, double-click the Sort items button in the design modeofthe Form1.cs file and add the following code snippet on its Click event:

    private void button3_Click(object sender, EventArgs e)

    {

    comboBox1.Sorted = true;

    }

    Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill combo boxbutton and then the Sort items button. The combo box appears sorted, as shown in Figure 2.34:

    Figure 2.34: Sorting the Items in a Combo Box

    You should know; however, that sorting a combo box can change the indices of the items in that combo box (unless they werealready in alphabetical order). After the sorting is finished, the first item in the newly sorted combo list has index 0, the nextindex 1, and so on.

    Storing Objects in the ComboBox ControlsBesides storing the data of primitive data types, you can also store the objects of a class in a combo box control.Lets create a new class, DataItem, in the ComboBoxSample application and store its objects in the ComboBoxcontrol. Listing 2.25 shows the code of the DataItemclass:

    Listing 2.25: Showing the Code of the DataItem Class

    public class DataItem

    {

    private float Data;

    private string Name;

    public DataItem(string NameArgument, float Value){

    Name = NameArgument;

    Data = Value;

    }

    public override string ToString()

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    34/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    64

    {

    return System.Convert.ToString(Name);

    }

    public float GetData()

    { return Data;

    }

    }

    In Listing 2.25, the ToString() method of the DataItemclass is overridden because this method is calledwhen the combo box needs to display the name of each item. In addition, a GetData()method is also added toget the internal, private data from the objects.

    When the form loads, we can create 21 objects of the DataItemclassfor example item 5 is named Item 5 andstore the internal value 5and place them in the combo box with the Items.Add()method. To do so, double-click the Store objects button in the design mode of the Form1.cs file and add the code, shown in Listing 2.26, onits Click event:

    Listing 2.26: Showing the Code to Store Objects using the Add() Method

    private void button4_Click(object sender, EventArgs e)

    {

    comboBox1.Items.Clear();

    DataItem[] Objects = new DataItem[21];int intLoopIndex = 0;

    for (intLoopIndex = 0; intLoopIndex

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    35/36

    Immediate Solutions

    65

    Figure 2.35: Storing Objects in Combo Box

    Let us learn some of the frequently used events of the combo box, such as TextChanged and

    SelectedIndexChangedevents.

    Handling theTextChangedandSelectedIndexChangedEventsCombo boxes are combinations of text boxes and list boxes, and the combination means that there are two sets ofinput events:

    TextChanged eventOccurs when the user types into the text box

    SelectedIndexChangedeventOccurs when the user uses the list box part of the combo box

    Unlike standard list boxes, you cannot make multiple selections in a list box of the combo box.

    The TextChanged Event

    When the user changes the text in a combo box, a TextChanged event occurs in the same way as it occurs whenthe user types in a standard text box. Write the code on the TextChanged event of the ComboBox control, asshown in the following code snippet:

    private void comboBox1_TextChanged(object sender, EventArgs e)

    {

    textBox1.Text = comboBox1.Text;}

    Press the F5 key on the keyboard to execute the application. When the form appears, click the Fill combo boxbutton and type a new item in the text box of the combo box, as shown in Figure 2.36:

    Figure 2.36: Displaying the Text in the Text Box

  • 7/29/2019 2.Chkbx,Rdbtn,Lstbx,Chklst,Cmbox

    36/36

    Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox

    66

    In Figure 2.36, whatever you type in the combo box is automatically displayed in the text box simultaneously.

    The SelectedIndexChanged Event

    When the selection changes in a combo box, a SelectionChanged event occurs, and you can use the

    SelectedIndex and SelectedItemproperties to get the index of the currently selected item and the itemitself. Generate the SelectedIndexChanged event of the combo box and add the code, as shown in Listing 2.28:

    Listing 2.28: Showing the Code for the SelectedIndexChangedEvent of the Combo Box

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (comboBox1.SelectedIndex > -1)

    {

    if (comboBox1.SelectedItem.GetType() == typeof(DataItem))

    {

    textBox1.Text = "The data for the item you selected is: " +

    ((DataItem)comboBox1.SelectedItem).GetData();

    }

    }

    }

    In Listing 2.28, when the user selects an item in the combo box, we can use the SelectedItemproperty to get

    the selected object, and the GetData() method of the selected object to get its stored data (note that we mustcast the item to an object of the DataItemclass first), which we display in a text box.

    Press the F5 key on the keyboard to execute the application. When the form appears, click the Storing objectsbutton and then select an item from the combo box, as shown in Figure 2.37:

    Figure 2.37: Displaying the Value in the TextBox on Selecting the Combo Box Items

    Now, lets summarize the main topics discussed in this chapter.

    SummaryIn this chapter, you have learned about some standard Windows Forms controls, such as RadioButton,CheckBox, ListBox, CheckedListBox, and ComboBox. You have also learned about their properties, methods,and events. Finally, you have learned to implement and use these form controls in various applications.

    In the next chapter, we continue our discussion on Windows Forms controls and learn about another set ofstandard controls, such as ListView, TreeView, ImageList, PictureBox, Panel, GroupBox, and TabControl.