All-In-One
Composite Default screen All-In-One
/ MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
19
19
User-Interface
Components
CHAPTER
19
In this chapter, you will
• Learn how to work with controls
• Explore the Toolbox controls
• Become familiar with common dialog boxes
• Learn how to create menus
• Be introduced to validation of user input
In this chapter, we will explore the properties and behaviors of the various controls in
the Toolbox. If you have been working with previous versions of the Visual C++ or
Visual Basic languages, you may want to travel quickly through this chapter. If you’re
less familiar with the Toolbox controls, you’ll probably want to spend a bit more time
exploring the material here.
The .NET Framework includes several basic controls that enhance the look of your
Windows applications. Knowing how to work with these controls is an important part
of creating applications that give the most assistance to the user. You may have worked
with several of these controls in previous versions of Microsoft Visual products—they
date back to the early days of Windows programming. However, you need to under-
stand and be able to work with the properties, methods, and events that are exposed to
the developer. For the exam, you will need to know how to work with groups of con-
trols. We will look at setting the properties of multiple controls, working with collec-
tions of controls, and configuring the order through which the controls are tabbed.
Of equal importance is the ability to add functional menus to your application.
Towards that goal, we will explore top-level menus, submenus, and context menus.
A context menu is one that appears when the user right-clicks somewhere within a form.
We will also investigate the events that are triggered by using the menus.
Microsoft will also test your understanding of providing user assistance in your appli-
cations. We will look at adding validation code that will determine the soundness of the
user’s input. Two validation techniques will be covered—using the ErrorProvider
control and the Validation event. User assistance can also mean providing meaning-
ful help to the application. With that goal in mind, we’ll look at the HelpProvider
control and talk about ToolTips.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:38 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
19
19
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:38 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
Anchoring a Control
One way to ensure that a control maintains its position when a form is resized is by set-
ting the Anchor property. By anchoring a control, you ask Visual C# to maintain the
distance between the control and the form. By setting the Anchor property to a certain
position, you will ensure a more pleasing outcome when resizing.
The following illustration shows our college project and the TabControl’s Anchor
property has been set to Top, Bottom, Left, Right. Notice the Anchor property drop-down
box—you can set the anchor to position at any combination of Top, Bottom, Left, and
Right. By default, the Anchor property is set to Top and Left. To clear any part of the
anchor, just click on the shaded rectangle.
PART IV
Let’s observe what happens when we resize the form. Try to resize your form when
the TabControl is set to anchor to Top, Bottom, Left, and Right. As you will see, things
are not quite right yet. The buttons are shifting to bizarre locations—as a matter of fact,
we have even lost the Edit button.
Go into the properties of the buttons now (select them as a group) and set the Anchor
property to Bottom and Left. Now when we run our application, the buttons stay down at
the bottom of the form when we resize.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:39 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
EXAM TIP By using a few panels on your form, you can set controls on the
panel and then align the controls using both the Anchor and Dock properties.
(You will see the Dock property in the next section.) You will still have to add
code for complicated forms, but if you recall resizing in earlier versions of Visual
C++ or Visual Basic, you will be pleased by the small amount of coding necessary.
Docking a Control
Another cool technique offered in Visual C# .NET is the docking of controls to ensure
their positions upon resizing. If you recall our study of the Visual Studio .NET environ-
ment, windows can be docked or undocked. Docking means that the window becomes
“attached” to a certain part of the background form and moves and sizes with the form.
We have taken our previous example and reverted the Anchor property back to its de-
fault of Top and Left, and we have set the Dock property of the TabControl. The Dock
property window gives you a choice of five different positions: Top, Left, Bottom, Right,
and Middle. Select the Left panel, and rerun the form. Notice that the TabControl is
“stuck” to the left side of the form and fills the entire side. There is now no space for our
buttons and, as such, they really become part of the TabControl, which is not our
desired result.
Again, you should note that it is the combination of the Dock and Anchor properties,
along with some tricky coding, that will achieve the final aesthetically pleasing result. If
you are a Java programmer, you may have spent some time with the different layout man-
agers, and you may find the Dock property to be similar to the BorderLayoutManager
whereby “controls” are set in the North, South, East, West, or Center of the form layout.
By experimenting with setting the Dock property and using panels to hold your controls,
you will find that C# has employed a very similar way of setting control positions and
holding them in that position when the form resizes.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:39 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
Table 19-1 illustrates the options that are available through the Format menu.
PART IV
Centers
Rights
Tops
Middles
Bottoms
to Grid
Make Same Size Width Allows multiple controls to be resized on the form.
Size to Grid
Height
Both
Horizontal Spacing Make Equal Adjusts the horizontal spacing between the controls.
Increase
Decrease
Remove
Vertical Spacing Make Equal Adjusts the vertical spacing between the controls.
Increase
Decrease
Remove
Center in Form Horizontally Controls the centering of the controls on the form.
Vertically
Order Bring to Front Determines whether a control will take a foreground
Send to Back spot, no matter what is placed in front of it.
Lock Controls Locks all the controls on the form and eliminates any
chance of moving or resizing the controls.
Table 19-1 The Format Menu
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:39 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:39 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
You can tell by looking through the code that the Location and Size properties have
been affected by our changes to the Visual Designer. Notice that this code is in the
InitializeComponent() method, which, as we discussed in the last chapter, is
the method that is called in the form’s constructor.
PART IV
One final option to quickly discuss is the Lock Controls option. When we set
the Locked property to True or select the Lock Controls option from the Format
menu (shown next), the controls are no longer capable of being moved or resized in the
Visual Designer.
EXAM TIP Microsoft will expect you to know how to lock controls for the
Windows exam. By setting the Lock property to True, you will find that the
controls are locked in position.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:40 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
19
19
When you run the college application, you will notice that you can tab through the
controls on the form. If you created the form by adding the controls in order of appear-
ance, meaning the TabControl first, the Add button second, and so on, the order in
which you tab is the order in which they were added to the form.
Let’s add a new button. We have aligned the Add, Edit, and Delete buttons and made
them the same size. The new button is added, visually, before the other three buttons.
Yet when you press the TAB key, the first stop is the Add button. It was added to the form
first, so it is the first stop.
We can configure the tab order by using the TabIndex property. The first control
added to the form has a TabIndex value of 0 (zero). The second control has a value of
1 (one), and so on. You can enter new values to change the tab order.
If you prefer, you can use the View menu to set tab order, as well. This is a very handy
technique that will save you a lot of time if your form has many controls that are out of
order. Follow these steps to configure tab order using the View menu:
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:40 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
If you want, you can tell C# not to stop at a particular control. Set the TabStop
property for that control to False, and you will see that the control is not part of the tab
order. A line of code like this will be added to the InitializeComponent() method
of the control:
PART IV
this.button1.TabStop = false;
As you can see, the .NET Framework has provided us with a number of valuable tools
that save hours of programming. Spend some time experimenting with these now, and
you will find your development time (from the GUI perspective) greatly reduced.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:40 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
Keep in mind that these are just some of the common events that can occur. Each
control will have its own list of specific events that have been created just for it. For
example, the Timer control has a Tick event that is unique to it.
Buttons
Including buttons on your form allows the user to select an activity. There are three dif-
ferent kinds of buttons that you can employ—the regular “Click here” type of button, a
radio button, and a check box. It may seem strange that we include radio buttons and
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:40 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
PART IV
A .NET button can have an image added to it. Notice the graphic to the left of the “De-
lete” text on the button. This graphic is added by configuring the Image property. We have
added one of the common bitmaps that are included with the Visual Studio .NET installa-
tion. If you are trying this yourself, you will notice that the graphic appears on top of the
text (which we also changed from “Buttonx” to “Delete”). By adjusting the ImageAlign
property, you can place the graphic to the left of the text (or wherever you want it to be).
TIP Notice the underlined “A” on the Add button. This is created by adding
an ampersand (&) in the Text property in front of the character you wish
underlined. The user can then use the ALT key along with the underlined
letter to access the button (instead of clicking on it).
To add the code that should be run when the user clicks on the button, double-click
the newly designed button. You will be taken to the code view of the main form. You
will see that two things have happened:
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:41 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
We can add our own code in the Click event that will perform the required Delete
operation. In Chapter 20, we will code this button to remove a record from the database.
A cool way to determine the valid properties, methods, and events for any control is
to type the name of the control in the code view window (for example, btnDelete),
and then press the period (.), which is also known as the dot operator. IntelliSense drops
down a list of all the properties, methods, and events for the control. You will be able to
determine whether a name is for a property, method, or event by observing the icon
beside the name. The hand holding a piece of paper denotes a property, the flying paper
signals a method, and the lightning bolt represents an event. A couple properties war-
rant mentioning:
• Enabled By setting this property to False, the button will display on the form
but will not be capable of receiving any user intervention activities.
• Visible This property determines whether the control will appear on the
form or not. This is a valuable property, because there will be times that a
control should not be visible, and you can control when it is actually displayed
programmatically.
Radio Buttons The look of the radio button is a far cry from the look of the But-
ton class; however, they derive from the same base class, ButtonBase. A radio button
is used when you want to give the user a choice of two or more mutually exclusive
options. In our example in the following illustration, the user can choose either Com-
puter Course or C# Course—of course, we know they’ll choose the C# course!
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:41 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
Table 19-3 identifies some of the more common properties and events for a
RadioButton.
Check Boxes A check box allows the user to select an option or answer a question.
The following illustration shows a check box that has been added to our college applica-
tion in the Visual Designer. The difference between a check box and a radio button has
PART IV
to do with the mutually exclusive options of a radio button. With a radio button, you
can select only one of the grouped options. By using check boxes, you allow the user to
select any number of options, and these options could be very different in nature.
In our example (in the preceding illustration), you can see that the check box is in an
indeterminate state (the check mark is grayed out). This is a common practice with Win-
dows applications. The check box can be selected (with a dark check mark), unselected
(no check mark), or unchanged (indeterminate). By default, however, you only allow
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:41 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
To display the check mark as a default value, set the Checked property to True.
Let’s look at the code that would toggle the CheckBox Checked property.
As you can see in this example, there are enum files (such as CheckState) that allow
us to use alphanumeric values to compare states (cbTest1.CheckState ==
CheckState.Unchecked). Always check with the Object Browser (View | Other
Windows | Object Browser) for these convenient classes.
Text Boxes
When you need the user to enter a value into your application, you can make use of
a TextBox. The control derives from the TextBoxBase class. You will also find a
RichTextBox control extending from TextBoxBase, which allows you to provide
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:41 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
PART IV
• ReadOnly Sets the TextBox to be a read-only text box. The user will be
unable to change the value in the TextBox.
• WordWrap Specifies that words will wrap if the text in the control exceeds the
width of the control. Used for multiple-line text boxes.
One of the nicer features of a TextBox is its ability to provide validation code. We
will examine this later in the chapter—just keep in mind that most of the events that you
will use for a TextBox belong to the validation type.
Rich Text Boxes The RichTextBox class uses a standard for displaying format-
ted text strings called Rich Text Format (RTF). This allows you to utilize formatting, such
as bold, italic, and underlining. Some properties are supported via the base class and
some are new to the RichTextBox:
• Redo and Undo Allows you to specify a True/False value that lets the user
undo or redo their keystrokes.
• DetectUrls Specifies that a URL will be treated as such and display as an
underlined link.
• SelectedRtf Allows the user to cut and paste between your application and
an application such as Microsoft Word and have the Rich Text Formatting
retained between applications.
This is just a sampling of some of the features of a RichTextBox. Figure 19-1 illus-
trates our application with a RichTextBox added. We have added a Button control
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:41 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
that will set a selected area of text to bold. The code to implement this in the Button
Click event is as follows:
When the button is clicked, whatever text is selected is converted to bold. In our ex-
ample, we selected the word “bolding” and then clicked the button. As you can see, the
text changes to bold font for just the word “bolding”. Obviously, this is a trivial example
of what you can do to effect formatting changes to the text in a RichTextBox. The code
demonstrates the SelectionFont property, which is just one of the selection proper-
ties available for use.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:41 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
PART IV
EXAM TIP Notice that the Caption property is not the property to use to
set the text of the label. You use the Text property in Visual Studio .NET.
We will not spend much time discussing the label controls since they are very basic
controls; however, it warrants looking at how you set the properties to support hyperlinks
for the LinkLabel control. In the InitializeComponent() method, the Designer
has added the following code:
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:42 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:42 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
PART IV
Figure 19-3 Using the DropDownStyle settings for a ComboBox control
You can see from Figure 19-3 that the Simple style presents one item in the box, while
both the DropDownList and DropDown styles allow you to drop down a predefined
number of items. The difference between DropDownList and DropDown has to do with
the data itself. DropDown style allows the user to type in the top line of the drop-down list
and DropDownList only lets the user select items that have been displayed.
Here are some important properties of the ListBox:
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:42 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
TIP The Items collection is also a property of the ComboBox and the
CheckedListBox.
These kinds of controls are great for presenting data retrieved from a back-end data-
base server to the user. In our example, we have simply added to the list by using the
Items collection in the Property Explorer. You can also add items programmatically at
run time using Items.Add. However, there are many times when your data will come
from an outside source, like Microsoft SQL Server 2000. In that case, you will find your-
self using the DataSource property. We will explore this in the next chapter.
Tab Controls
If you’ve been looking closely at the form we’ve been using for all of the demonstrations
so far, you will notice that there is a tab control in the background of the form. It has
served as an organization tool so that we can separate parts of the application. Each tab
across the top of the TabControl is called a TabPage.
You can work with the properties of each TabPage by clicking on the ellipsis (…)
beside the TabPages property. When you select the TabControl, you will see two
links at the bottom of the Properties window—Add Tab and Remove Tab. You can use
these buttons as shortcuts to adding new TabPages to the TabControl. However, to
control the various properties of each individual page, you need to use the TabPage Col-
lection Editor, shown next.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:42 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
• HotTrack This property causes the tab page’s text to change color as the
mouse passes over the tab.
• SuspendLayout() This is really a method of the Control class, and it
temporarily suspends the layout for the control. You would use this method
while you make many adjustments to the layout of a control:
tabControl1.SuspendLayout();
For example, at some point in your application, you may need to change the
Size or Location properties of a control. Suspend the layout first, make your
changes, and when you are finished, you can call this method:
tabControl1.ResumeLayout();
PART IV
// add code here to insert the controls that will sit on the Tab Page
// For example :
Button b = new Button;
tpStudentMarks.Controls.Add (b);
// Add the new Tab Page to the Tab Control
tcTabControl.Controls.Add (tpStudentMarks);
Status Bars
The StatusBar control is usually used to display information to the user in an unob-
trusive manner. By docking the status bar at the bottom of your application, you can set
panels into the bar that will display different information. By default, the StatusBar
has a single panel (or section for information). By adding panels to the Panels collec-
tion, you can display more information.
You can access the StatusBarPanel Collection Editor to modify the properties of the
panels of the StatusBar. You can get to this editor by clicking the ellipsis (…) beside
the Panels property.
Each panel in a status bar has a zero-based index value, so the first panel has an index
value of 0. If we wanted to programmatically change the information in the third panel ,
we would add the following line of code:
EXAM TIP If you are adding a status bar to your application, and you are
disappointed when you run the program because the panels of the status bar
do not show, don’t forget to set the ShowPanels property to True—its
default value is False.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:43 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
• The Canadian flag button is the PushButton style—a typical toolbar button.
• The American flag button is the ToggleButton style, which is either pressed or
not pressed.
• The Swedish flag button is the DropDownButton style, which gives extra
options when the drop-down arrow is clicked.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:43 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
Notice, as well, that our toolbar has images on each button. This is accomplished by
adding the ImageList control to your project, and it is simply a holder for images.
When you add the control to your application, a little icon appears below the form win-
dow (unlike in Visual Studio 6, where the control actually sat on your form, but was
invisible at run time). By using the ImageList Collection Editor, you can add any number
of images to your application. When you use the images, you reference the ImageList. By
using a property named ImageIndex, you select from a list of images attached to a par-
ticular ImageList. The ImageList is actually set via the ImageList property of the
ToolBar itself. Once you have set the ImageList property, you will have access to all
the images associated with the ImageList, and you will be able to select them from the
ToolBarButton Collection Editor.
We will examine the ButtonClick event associated with toolbar buttons later in
this chapter when we introduce menus and the handling of menu events.
Dialog Boxes
PART IV
Using a dialog box is a great way to interact with the user. You may want to simply pre-
sent some information to the user and wait for a response, but it might also get more
complicated than that. In some cases, you will want to ask the user to set common win-
dow properties. For example, the user may choose to customize your application by
choosing their desired font or colors. This can be accomplished by using the predefined
dialog boxes that come with the .NET Framework. In the Visual Studio 6 world, these
were called common dialog boxes and were part of an ActiveX control. Of course, we are no
longer in that world, and the predefined dialog boxes are now class files.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:43 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
19
19
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:43 PM
Color profile: Generic CMYK printer profile
All-In-One
Composite Default screen All-In-One
/ MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
19
19
As you can see, there are enumerations that help make the appearance choices for the
message box. These include the following:
The Show() method of the MessageBox class is overloaded so that you can display
PART IV
the default message box with only a message and the OK button, or you can create an
elaborate box using all of the options.
NOTE Message boxes are modal dialog boxes meaning the user must
respond before they will be returned to the rest of the application. Some
dialog boxes are modeless, and they will allow the application to continue
while the dialog box is running.
You may want to examine the result returned after displaying the message box. The
user clicks one of the buttons and your application can deal with the returned value.
In order to do this, you make use of the DialogResult class.
DialogResult result = MessageBox.Show (this, "Click Yes, No or
Cancel",,MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Cancel)
{
// Write your cancellation code here
}
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:44 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
When you click the Save button, the Save File As dialog box is presented. The user can
then navigate through the file system and select the file they need saved. The control
ensures that the file is saved properly and all error handling is done correctly. For exam-
ple, if the user tries to save a file in a location where the file already exists, a warning
message will appear informing the user that this action will override the existing file.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:44 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
EXAM TIP Microsoft will not likely ask you to add controls at design time
using a visual editor—you will need to know the properties and events that
we have just covered in this chapter. However, it is a good idea to have a firm
grasp on adding controls at run time, since there will be direct questions on
adding controls in this fashion.
PART IV
All the controls on a Windows Form (or in a container control like the Panel) are
part of a collection object. The object itself is of type ControlCollection. The
ControlCollection object represents a collection of control objects—buttons, list
boxes, and so on. You can access the controls by using the Controls property.
The following list demonstrates some of the capabilities of the collection object:
To test whether a particular control is part of the collection, try the following example
code:
if (form1.Controls.Contains (btnClickMe))
{
MessageBox.Show("We found the button");
}
You can also clear the full collection by using this line:
form1.Controls.Clear();
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:44 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
tabPage1.Controls.Clear();
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:44 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
This code section will add the new control to the Controls collection on the tab
page—the next step is, of course, to add the extra functionality.
This section has introduced the typical controls with which any Windows program-
mer will work. Experiment with each one of them—Microsoft expects you to have a full
understanding of their functionality.
PART IV
Now that we’ve discussed all the common controls, it’s time to move into another big
arena for visual presentation of your application. Nearly every Windows Forms program
has a menu attached to it—menus give the user a list of options that are available within
the application. There are two types of menus in the .NET world—the regular menu that
you see attached to the top of any application window, and the menu that appears when
you right-click on something. The first type is a MainMenu, while the right-click menu is
a ContextMenu. We will start this section of the chapter by looking at the MainMenu
object and then conclude the section discussing the ContextMenu.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:44 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
• To create a menu separator, such as the one between Close and Page Setup in
Figure 19-8, type a hyphen (-) in the “Type here” prompt. This will insert the
separator, which is really a separate menu item.
• If you want to create submenus, simply type in the “Type here” area that is
displayed to the right of the current area. The control will add the appropriate
arrows to indicate a submenu.
• The MainMenu is made up of MenuItem children objects. The hierarchy is
then created between parent and child objects.
• You can create menu item shortcuts by adding an ampersand (&) to the text of
the menu item. Notice in Figure 19-9 that by placing the ampersand in front of a
character, that character becomes the shortcut character. The user can then invoke
that menu item by pressing a combination of ALT and the shortcut character.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:45 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
PART IV
Figure 19-9 Creating a shortcut character
By selecting the MainMenu from your form, you can examine the properties of each
MenuItem object. You can set options such as these:
• Checked Displays the menu item with a check mark in front of it.
• DefaultItem Specifies the menu item as the default.
• Enabled Grays out the menu item and makes it inaccessible.
• RadioCheck Does the same as Checked only with a radio button.
• Shortcut and ShowShortcut Deals with the shortcut keys, such as
function keys and combinations of function and SHIFT, ALT, CTRL, and so on.
• Text Specifies the actual text of the menu item.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:45 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
The next step is to construct each of these objects. This happens in the method:
InitializeComponent().
We have just looked at a very standard Windows Forms menu, but you may have
need of a menu that spans from the right of the document to the left. In that case, add
the following code to the MainMenu object:
MainMenu1.RightToLeft = RightToLeft.Yes;
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:45 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
Context Menus
You know the menus that pop up whenever you right-click on a form? These are called
context menus—so called because they respond to the context of the item that is in the
foreground. The control that is used to create a context menu is ContextMenu. At
design time, you can add a context menu to your form from the toolbox. It is a control
that does not reside on the form, similar to a MainMenu. Once the context menu is
added to the application, you can set the property of the control to which you wish to
associate the context menu. Figure 19-10 illustrates the instance of a context menu
added to our project (at the bottom of the screen) and the ContextMenu property of
the TextBox set to that instance.
PART IV
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:45 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
The actual menu items are built much as a MenuItem is added to your form. At the top
of your form will be a ContextMenu instance (invisible at run time) that allows you to
type in the menu items. When we run our revised application, the user can right-click on
the Student Name text box and see our context menu, as shown in Figure 19-11.
You can add a context menu at run time by adding MenuItem objects to the
ContextMenu collection of menu items called MenuItems.
EXAM TIP New to the .NET Framework is the ability to add images to menu
items. You simply override the OnPaint() method of the MenuItem
object and draw your image.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:45 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
Of course, you should also investigate ways of using .NET controls that are designed to
restrict user input. But that’s another story for another book. We will deal with the two
methods that you are likely to encounter on the Microsoft exam.
Validating Events
Certain controls cause a validating event to fire when they are exited. For example, as a
user moves from text box to text box on a form, the validating event can be used to
ensure that the user has entered correct data.
We have added an extra text box to our Students tab page (see Figure 19-12). A short-
cut, when using the Visual Designer, to register a new event with a handler is to click the
lightning bolt (for events) in the Properties Explorer.
PART IV
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:46 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
Inside the method, you can add code that will test the value entered by the user and
set the Cancel property of the CancelEventArgs object to True if the data is not
valid. This has the effect of eliminating the tab or click to the next control and gives you
an opportunity to present an error message to the user. The user will then have to correct
the data and try to move off the control again. Validation will continue to happen until
your method is successfully completed.
Here is an example of validation code:
{
if ( // validation test here)
{
e.Cancel = true;
MessageBox.Show ("Invalid data!");
}
}
ErrorProvider Control
The ErrorProvider control lets you display an error message if the information
entered by the user is in error. By using the ErrorProvider, you can set an icon next
to the control that contains the data in error. This is more desirable than using a message
box, because as soon as the user dismisses the message box, they no longer have a record
of the error. A “message” created with the ErrorProvider stays on the form until the
correction to the data is made.
Figure 19-13 demonstrates our validation of the first text box. Notice the big question
mark beside the text box. The ErrorProvider has placed it there.
TIP Move your mouse over the question mark to see the error message.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:46 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
PART IV
Figure 19-13 Using the ErrorProvider control
Summary
We’ve come a long way in this chapter. By using all the different controls available in the
Toolbox, we have been able to create visually pleasing and very functional Windows
Forms applications. It warrants mentioning again that you should be very comfortable
with all of the concepts in this chapter. Microsoft assumes you are extremely proficient
at using the basic controls, creating menus, and working with error validation. On the
CD that comes with this book, you can review the entire code for our college project.
In the next chapter, we will work with back-end SQL Server data and continue to
build upon our college application. We will access student and course information from
the database and demonstrate how to access the data and how to present it. The next
chapter is a very significant one for the Microsoft exams. You will find that they like to
test you on your data-access knowledge. So once you’ve tried the following test ques-
tions, fasten your seat belts and join us on a data exploration.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:47 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:47 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
PART IV
B. MenuItem m = new MenuItem();
contextMenu1.MenuItem.Add (m);
C. MainMenu m = new MainMenu();
contextMenu1.MenuItems.Add (m);
D. MainMenu m = new MainMenu();
contextMenu1.MenuItem.Add (m);
8. To produce a dialog box similar to the Windows Print dialog box, which of the
following controls would you use?
A. PrintPreviewDialog
B. PrintDialog
C. PrintBox
D. SetupPrintDialog
9. Which property of the CheckedListBox allows you to preset the maximum
number of items that can be selected?
A. MaxItems
B. MaximumItems
C. SelectionItems
D. SelectionMode
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:47 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
19
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:47 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
19
Test Answers
1. C.
2. D. The syntax error is in the Caption property of the TabPage—it should be
the Text property.
3. B. You must add the tab page to the Controls collection of the tab control.
4. D. The ErrorProvider will place the error message next to the text box.
5. C. The Validating event allows you to validate the user input.
6. C.
PART IV
7. A. The collection is called MenuItems, and you must create MenuItem objects.
8. B.
9. D.
10. B. A runtime error will occur since the Panel collection of the StatusBar is
zero-based.
11. C. Show is a property, not a method.
12. D. None of the above. You must use this line of code:
System.Diagnostics.Process.Start ("http://www.microsoft.com");
13. B. The property is SelectionFont, and the Font constructor takes
FontStyle.Bold.
14. D.
15. B.
P:\010Comp\All-in-1\443-6\ch19.vp
Friday, August 23, 2002 5:02:47 PM