Windows Forms Controls: Radiobutton, Checkbox, Listbox, Checkedlistbox, and Combobox
Windows Forms Controls: Radiobutton, Checkbox, Listbox, Checkedlistbox, and Combobox
In Depth
In the previous chapter, you learned about some of the commonly used controls, such as Button, Label,
TextBox, RichTextBox, and MaskedTextBox. This chapter describes some of the standard Windows Forms
controls, RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox. These controls form the basic layout
of an application using which users interact with the application. You would call these controls as selection
controls since all of them are primarily used for selection purpose. The RadioButton control is used in a situation
where you want to select only one option from the group of options; whereas, the CheckBox control allows you
to select multiple options from the group. The ListBox control lists all the items and allows you to select the
items from the list. The CheckedListBox control is similar to the ListBox control; in addition, it displays check
boxes beside every item in the list. Instead of selecting the item, you can select the check box of that particular
item you want to select the CheckedListBox control. The ComboBox control is similar to the ListBox control; the
difference 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 you
some idea about the most commonly used properties, methods, and events of the control. This chapter describes
the 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.
Let’s start our discussion with the RadioButton control.
32
In Depth
33
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
deselect it. When you select the check box, it holds the value true; and it holds the value false when you
deselect 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 or
unknown selection needs to be represented. Consider an example, where a single check box is used to change
the 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 becomes
difficult to specify the current state of the check box. This state is known as the indeterminate state. To enable
indeterminate state, set the ThreeState property of the check box to true. Figure 2.2 shows check boxes as
they appear at design time:
34
In Depth
A CheckBox control can display image, corresponding text associated with the check box, or both
simultaneously. Use the ImageAlign and TextAlign properties to determine the location where the caption
and 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 check
box. Let’s now explore the ListBox control.
35
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
36
In Depth
The items in list boxes are stored in the Items collection. The Items.Count property holds the number of
items in the list (the value of the Items.Count property is always one more than the largest possible
SelectedIndex value because selected index is zero-based, i.e., the selected index always starts with
zero 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 box
simultaneously with the AddRange() method. In addition, you can add and remove items to the list by using
the Items property at design time.
You can also support multiple selections in list boxes. The SelectionMode property determines the number of
items that can be selected at a time and can hold one of the following values:
MultiExtended—Specifies that multiple items can be selected and the user can use the SHIFT, CTRL, and
arrow keys to make selections
MultiSimple—Specifies that multiple items can be selected
None—Specifies that no items can be selected
One—Specifies 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, the
SelectedItems property to access the selected items, and the SelectedIndices property to access the
selected indices.
37
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
38
In Depth
Similar to standard list boxes, you can access the items in a checked list box using the Items property. To check
an item, the user has to double-click a check box by default, unless you set the CheckOnClick property to
true, 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 the CheckedItems and CheckedIndices properties.
You can also use the GetItemChecked() method to verify whether or not an item is checked. In addition, you
can use the ItemCheck event to handle check events, and the SetItemChecked() method to check or uncheck
items.
Checked list boxes can also support three states by using the CheckState enumeration—Checked,
Indeterminate, and Unchecked. You must set the state of Indeterminate in the code because the user
interface does not provide a way of doing so. To use three-state check boxes, you can use the
GetItemCheckState and SetItemCheckState() methods instead of the GetItemChecked and
SetItemChecked() methods.
39
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
40
In Depth
You can use the Text property of a combo box to set and access the text in the text box of the combo box. You
can use the SelectedIndex property to get the selected list item. You can change the selected item by changing
the SelectedIndex value in the code, which displays the corresponding item in the text box portion of the
combo box. As with list boxes, if no items are selected, the SelectedIndex value is set to -1. If the first item in
the list is selected, the SelectedIndex value is set to 0.
In addition, you can also use the SelectedItem property, 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 SelectedIndex
value 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 remove
items 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 property
determines the style of the combo box to be displayed. You can set this property to display the list box of the
combo box in the following combo box styles:
DropDown—Specifies that the text portion is not editable and you must use an arrow to see the drop-down
list box. It is the default drop-down style.
DropDownList—Specifies that the text portion is editable and the user can use the arrow key to view the
list.
Simple—Specifies 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 the
BeginUpdate() and EndUpdate() methods to add a large number of items to the combo box without
redrawing 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 use
the SelectedIndex property to get or set the index of the currently selected item, and the SelectedItem
property to get or set the selected item. You can also use the Text property to specify the string displayed in the
text box part of the combo box.
41
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
Immediate Solutions
Using the RadioButton Control
As mentioned in the In Depth section, a RadioButton control allows a user to select one item from an exclusive
group of items. Let us see some of its properties in action by creating an application, named
RadioButtonSample (available in the CD-ROM). This example contains a sample user interface form with
three 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, a
message box displays a message indicating the selected radio button and at the same time, all the radio buttons
are 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
Let’s explore these in detail next.
Figure 2.6: Displays the Text Set for the Radio Buttons
42
Immediate Solutions
Let’s 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 by
default 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 shown
in Figure 2.7:
43
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
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 button
left, 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 radio
button. Observe that the button aligns to the right of the form, as shown in Figure 2.9:
44
Immediate Solutions
45
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
7. Press the F5 key on the keyboard to execute the application. The output of the application appears, as
shown in Figure 2.11:
Figure 2.11: Displays the Text Set for the Check Boxes
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 in
Figure 2.12:
46
Immediate Solutions
if (checkBox2.Checked == true)
47
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
{
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;
}
}
48
Immediate Solutions
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 CheckBox
controls. Let us now see how to use the ListBox control.
Finally, a text box displays the selected item in a list box and a label displays the total number of items in the list
box.
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 SelectedIndexChanged event
9. Remove items from the ListBox controls
Let’s understand these in detail next.
49
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
50
Immediate Solutions
Note that when you add items in a list box, they are stored by index. If you are required to add an item at a
specified index, suppose at the middle of an already existing items list, you need to have two pieces of
information – the item to be added and its index number. In such a case, you use the Insert() method for
adding 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.
51
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
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 and
then click the Get indexes button. You can see the result, as shown in Figure 2.18:
You should know; however, that sorting a list box can change the indices of the items in that list box (unless they were already
in 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.
52
Immediate Solutions
ListBox controls support multiple selections if you set their SelectionMode property to either MultiSimple or MultiExtended. Use
the 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.
53
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
MultiExtended—Enables selection of multiple items, and the user can use the SHIFT, CTRL, and arrow
keys to make selections
MultiSimple—Enables selection of multiple items
None—Prevents you to select items
One—Enables 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 you
can use to set some items in the list box selected. The code for selecting the items of a list box at runtime is
highlighted 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 <= 20; intLoopIndex++)
{
listBox1.Items.Add("Item " + intLoopIndex.ToString());
}
listBox1.SetSelected(1, true);
listBox1.SetSelected(3, true);
}
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 the items in the first list box. You can see the output, as shown in
Figure 2.22:
54
Immediate Solutions
55
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
3. Double-click the Clear list box button in the design mode of the Form1.cs file and add the following code
snippet 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 box
button and then the Clear list box button to clear all the items from the list box, as shown in Figure 2.25:
56
Immediate Solutions
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:
57
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
58
Immediate Solutions
We have set the CheckOnClick property for the CheckedListBoxSample example in this chapter to true (the default setting for
this property is false), so all it takes is one click to generate an ItemCheck event. By default, however, a double-click would be
needed.
59
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
60
Immediate Solutions
the list. Following are the settings for the DropDownStyle property of the combo box (these are members of the
ComboBoxStyle 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.
Simple—Includes 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 the
list.
DropDownList—Includes only drop-down list and the user can only select the existing value from the
drop-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 DropDownStyle
property to Simple in the Properties window of the combo box:
61
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
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 the
DropDownStyle property of the combo box to DropDownList. In this style of combo boxes, the user cannot type into the text
part of the control.
Figure 2.33: Displaying the Total Number of Items in the Combo Box
The following topic deals with the sorting of the items in a combo box.
62
Immediate Solutions
You should know; however, that sorting a combo box can change the indices of the items in that combo box (unless they were
already in alphabetical order). After the sorting is finished, the first item in the newly sorted combo list has index 0, the next
index 1, and so on.
63
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
{
return System.Convert.ToString(Name);
}
public float GetData()
{
return Data;
}
}
In Listing 2.25, the ToString() method of the DataItem class is overridden because this method is called
when the combo box needs to display the name of each item. In addition, a GetData() method is also added to
get the internal, private data from the objects.
When the form loads, we can create 21 objects of the DataItem class—for example item 5 is named Item 5 and
store the internal value 5—and 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, on
its 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 <= 20; intLoopIndex++)
{
Objects[intLoopIndex] = new DataItem("Item " + intLoopIndex,
System.Convert.ToSingle(intLoopIndex));
comboBox1.Items.Add(Objects[intLoopIndex]);
}
comboBox1.Text = "Select one...";
}
You can use another method to add objects to the combo box that is the AddRange() method. The following
topic deals with the same.
64
Immediate Solutions
Unlike standard list boxes, you cannot make multiple selections in a list box of the combo box.
65
Chapter 2: Windows Forms Controls: RadioButton, CheckBox, ListBox, CheckedListBox, and ComboBox
In Figure 2.36, whatever you type in the combo box is automatically displayed in the text box simultaneously.
Figure 2.37: Displaying the Value in the TextBox on Selecting the Combo Box Items
Now, let’s summarize the main topics discussed in this chapter.
Summary
In 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 of
standard controls, such as ListView, TreeView, ImageList, PictureBox, Panel, GroupBox, and TabControl.
66