
Pro CSharp And The .NET 2.0 Platform (2005) [eng]
.pdf
714 CHAPTER 21 ■ PROGRAMMING WITH WINDOWS FORMS CONTROLS
Fun with CheckedListBoxes
Now that you have explored the basic Button-centric widgets, let’s move on to the set of list selection–centric types, specifically CheckedListBox, ListBox, and ComboBox. The CheckedListBox widget allows you to group related CheckBox options in a scrollable list control. Assume you have added such a control to your CarConfig Form that allows users to configure a number of options regarding an automobile’s sound system (see Figure 21-9).
Figure 21-9. The CheckedListBox type
To insert new items in a CheckedListBox, call Add() for each item, or use the AddRange() method and send in an array of objects (strings, to be exact) that represent the full set of checkable items. Be aware that you can fill any of the list types at design time using the Items property located on the Properties window (just click the ellipsis button and type the string values). Here is the relevant code within InitializeComponent() that configures the CheckedListBox:
private void InitializeComponent()
{
...
// checkedBoxRadioOptions
//
this.checkedBoxRadioOptions.Items.AddRange(new object[] { "Front Speakers", "8-Track Tape Player",
"CD Player", "Cassette Player",
"Rear Speakers", "Ultra Base Thumper"});
...
this.Controls.Add (this.checkedBoxRadioOptions);
}
Now update the logic behind the Click event for the Confirm Order button. Ask the CheckedListBox which of its items are currently selected and add them to the orderInfo string. Here are the relevant code updates:
private void btnOrder_Click (object sender, EventArgs e)
{



CHAPTER 21 ■ PROGRAMMING WITH WINDOWS FORMS CONTROLS |
717 |
widget to the CarConfig Form that allows a user to enter the name of a preferred salesperson. If the salesperson in question is not on the list, the user can enter a custom name. One possible UI update is shown in Figure 21-12 (feel free to add your own salesperson monikers).
Figure 21-12. The ComboBox type
This modification begins with configuring the ComboBox itself. As you can see here, the logic looks identical to that for the ListBox:
private void InitializeComponent()
{
...
// comboSalesPerson
//
this.comboSalesPerson.Items.AddRange(new object[] { "Baby Ry-Ry", "Dan \'the Machine\'",
"Danny Boy", "Tommy Boy"});
...
this.Controls.Add (this.comboSalesPerson);
}
The update to the btnOrder_Click() event handler is again simple, as shown here:
private void btnOrder_Click (object sender, EventArgs e)
{
//Build a string to display information. string orderInfo = "";
...
//Use the Text property to figure out the user's salesperson. if(comboSalesPerson.Text != "")
orderInfo += "Sales Person: " + comboSalesPerson.Text + "\n";
else
orderInfo += "You did not select a sales person!" + "\n";
...
}


CHAPTER 21 ■ PROGRAMMING WITH WINDOWS FORMS CONTROLS |
719 |
Setting the Form’s Default Input Button
Many user-input forms (especially dialog boxes) have a particular Button that will automatically respond to the user pressing the Enter key. For the current Form, if you wish to ensure that when the user presses the Enter key, the Click event handler for btnOrder is invoked, simply set the Form’s AcceptButton property as so:
//When the Enter key is pressed, it is as if
//the user clicked the btnOrder button. this.AcceptButton = btnOrder;
■Note Some Forms require the ability to simulate clicking the Form’s Cancel button when the user presses the Esc key. This can be done by assigning the CancelButton property to the Button object representing the Cancel button.
Working with More Exotic Controls
At this point, you have seen how to work most of the basic Windows Forms controls (Labels, TextBoxes, and the like). The next task is to examine some GUI widgets, which are a bit more high-powered in their functionality. Thankfully, just because a control may seem “more exotic” does not mean it is hard to work with, only that it requires a bit more elaboration from the outset. Over the next several pages, we will examine the following GUI elements:
•MonthCalendar
•ToolTip
•TabControl
•TrackBar
•Panel
•UpDown controls
•ErrorProvider
•TreeView
•WebBrower
To begin, let’s wrap up the CarConfig project by examining the MonthCalendar and ToolTip controls.
Fun with MonthCalendars
The System.Windows.Forms namespace provides an extremely useful widget, the MonthCalendar control, that allows the user to select a date (or range of dates) using a friendly UI. To showcase this new control, update the existing CarConfig application to allow the user to enter in the new vehicle’s delivery date. Figure 21-14 shows the updated (and slightly rearranged) Form.

720 CHAPTER 21 ■ PROGRAMMING WITH WINDOWS FORMS CONTROLS
Figure 21-14. The MonthCalendar type
Although the MonthCalendar control offers a fair bit of functionality, it is very simple to programmatically capture the range of dates selected by the user. The default behavior of this type is to always select (and mark) today’s date automatically. To obtain the currently selected date programmatically, you can update the Click event handler for the order Button, as shown here:
private void btnOrder_Click (object sender, EventArgs e)
{
//Build a string to display information. string orderInfo = "";
...
//Get ship date.
DateTime d = monthCalendar.SelectionStart;
string dateStr = string.Format("{0}/{1}/{2}", d.Month, d.Day, d.Year); orderInfo += "Car will be sent: " + dateStr;
...
}
Notice that you can ask the MonthCalendar control for the currently selected date by using the SelectionStart property. This property returns a DateTime reference, which you store in a local variable. Using a handful of properties of the DateTime type, you can extract the information you need in a custom format.
At this point, I assume the user will specify exactly one day on which to deliver the new automobile. However, what if you want to allow the user to select a range of possible shipping dates? In that case, all the user needs to do is drag the cursor across the range of possible shipping dates. You already have seen that you can obtain the start of the selection using the SelectionStart property.
The end of the selection can be determined using the SelectionEnd property. Here is the code update:

CHAPTER 21 ■ PROGRAMMING WITH WINDOWS FORMS CONTROLS |
721 |
private void btnOrder_Click (object sender, EventArgs e)
{
//Build a string to display information. string orderInfo = "";
...
//Get ship date range....
DateTime startD = monthCalendar.SelectionStart; DateTime endD = monthCalendar.SelectionEnd; string dateStartStr =
string.Format("{0}/{1}/{2}", startD.Month, startD.Day, startD.Year); string dateEndStr =
string.Format("{0}/{1}/{2}", endD.Month, endD.Day, endD.Year);
// The DateTime type supports overloaded operators! if(dateStartStr != dateEndStr)
{
orderInfo += "Car will be sent between " + dateStartStr + " and\ n" + dateEndStr;
}
else // They picked a single date.
orderInfo += "Car will be sent on " + dateStartStr;
...
}
■Note The Windows Forms toolkit also provides the DateTimePicker control, which exposes a MonthCalendar from a DropDown control.
Fun with ToolTips
As far as the CarConfig Form is concerned, we have one final point of interest. Most modern UIs support tool tips. In the System.Windows.Forms namespace, the ToolTip type represents this functionality. These widgets are simply small floating windows that display a helpful message when the cursor hovers over a given item.
To illustrate, add a tool tip to the CarConfig’s Calendar type. Begin by dragging a new ToolTip control from the Toolbox onto your Forms designer, and rename it to calendarTip. Using the Properties window, you are able to establish the overall look and feel of the ToolTip widget, for example:
private void InitializeComponent()
{
...
// calendarTip
//
this.calendarTip.IsBalloon = true; this.calendarTip.ShowAlways = true;
this.calendarTip.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
...
}
To associate a ToolTip with a given control, select the control that should activate the ToolTip and set the “ToolTip on” property (see Figure 21-15).

722 CHAPTER 21 ■ PROGRAMMING WITH WINDOWS FORMS CONTROLS
Figure 21-15. Associating a ToolTip to a given widget
At this point, the CarConfig project is complete. Figure 21-16 shows the ToolTip in action.
Figure 21-16. The ToolTip in action
■Source Code The CarConfig project is included under the Chapter 21 directory.
Fun with TabControls
To illustrate the remaining “exotic” controls, you will build a new Form that maintains a TabControl. As you may know, TabControls allow you to selectively hide or show pages of related GUI content via clicking a given tab. To begin, create a new Windows Forms application named ExoticControls and rename your initial Form to MainWindow.

CHAPTER 21 ■ PROGRAMMING WITH WINDOWS FORMS CONTROLS |
723 |
Next, add a TabControl onto the Forms designer and, using the Properties window, open the page editor via the TabPages collection (just click the ellipsis button on the Properties window). A dialog configuration tool displays. Add a total of six pages, setting each page’s Text and Name properties based on the completed TabControl shown in Figure 21-17.
Figure 21-17. A multipage TabControl
As you are designing your TabControl, be aware that each page is represented by a TabPage object, which is inserted into the TabControl’s internal collection of pages. Once the TabControl has been configured, this object (like any other GUI widget within a Form) is inserted into the Form’s Controls collection. Consider the following partial InitializeComponent() method:
private void InitializeComponent()
{
...
// tabControlExoticControls
//
this.tabControlExoticControls.Controls.Add(this.pageTrackBars);
this.tabControlExoticControls.Controls.Add(this.pagePanels);
this.tabControlExoticControls.Controls.Add(this.pageUpDown);
this.tabControlExoticControls.Controls.Add(this.pageErrorProvider);
this.tabControlExoticControls.Controls.Add(this.pageTreeView);
this.tabControlExoticControls.Controls.Add(this.pageWebBrowser); this.tabControlExoticControls.Location = new System.Drawing.Point(13, 13); this.tabControlExoticControls.Name = "tabControlExoticControls"; this.tabControlExoticControls.SelectedIndex = 0; this.tabControlExoticControls.Size = new System.Drawing.Size(463, 274); this.tabControlExoticControls.TabIndex = 0;
...
this.Controls.Add(this.tabControlExoticControls);
}
Now that you have a basic Form supporting multiple tabs, you can build each page to illustrate the remaining exotic controls. First up, let’s check out the role of the TrackBar.
■Note The TabControl widget supports Selected, Selecting, Deselected, and Deselecting events. These can prove helpful when you need to dynamically generate the elements within a given page.