Ch19

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Ch19 as PDF for free.

More details

  • Words: 12,741
  • Pages: 41
Color profile: Generic CMYK printer profile Composite Default screen All-In-One 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

19

CHAPTER

User-Interface Components 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 understand 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 controls. We will look at setting the properties of multiple controls, working with collections 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 applications. 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 meaningful help to the application. With that goal in mind, we’ll look at the HelpProvider control and talk about ToolTips.

1 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 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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

2

Working with Controls There are some common features of controls that warrant discussing in this chapter. The problem of programmatically resizing controls when the form resizes has traditionally been a difficulty that GUI developers face. In this section, we will look at how C# resolves this issue. You will also find times that you want to align controls to the position of the form. You may also want to designate the control with focus, making it the “active” control that responds to the ENTER key being pressed, or making it the selected control. Visual C# .NET also now has the capability of docking controls, much like windows can be docked.

Specifying a Control’s Location on a Form When a form is capable of being resized by the user, you need to be aware of how your controls will be positioned after the form is resized. When the user resizes the form, the default behavior is for the controls to maintain their position and size, but this may not be the desired outcome. Consider the first illustration, the start of our college application. We have a tabbed control that should expand when the form resizes, and a row of buttons at the bottom of the form that we would like to anchor to the bottom of the form accordingly. However, when the form is resized, the outcome is as shown in the second illustration.

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 screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

3 In the resized form, the TabControl (with the two tabs—Student and Courses) remains at its original size, and the buttons retain their alignment and size beneath the TabControl. In most cases, we would prefer the TabControl to size according to the resizing of the form, and we would like the buttons to do the same.

Anchoring a Control One way to ensure that a control maintains its position when a form is resized is by setting 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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

4 Just a word of warning—this won’t solve all of your resizing problems. You may still have to be creative with complicated forms. You may need the help of the Dock property (covered in the next section) and some coding. 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 environment, 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 default 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 managers, 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.

Aligning Controls on a Form If you are coding your form within Visual Studio .NET, you will find that you can use the Format menu to set options for working with your controls. When you work with the Format menu, you set the options in terms of a primary control. For example, we will select the three buttons on our form and make sure that the last button selected is the “Add” button. This will become the primary control to which the other controls align. Observe the next illustration—we selected the controls using the CTRL key and choosing the Add button last, and you can see that the primary control has dark resizing handles around it.

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 screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

5

Table 19-1 illustrates the options that are available through the Format menu.

Submenu Item

Description

Align

Lefts Centers Rights Tops Middles Bottoms to Grid Width Size to Grid Height Both Make Equal Increase Decrease Remove Make Equal Increase Decrease Remove Horizontally Vertically Bring to Front Send to Back

Aligns all controls to the primary control.

Make Same Size

Horizontal Spacing

Vertical Spacing

Center in Form Order Lock Controls Table 19-1

The Format Menu

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:39 PM

Allows multiple controls to be resized on the form.

Adjusts the horizontal spacing between the controls.

Adjusts the vertical spacing between the controls.

Controls the centering of the controls on the form. Determines whether a control will take a foreground spot, no matter what is placed in front of it. Locks all the controls on the form and eliminates any chance of moving or resizing the controls.

PART IV

Menu Item

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

6 Let’s work with the Format menu. Start with a form where the buttons are all different sizes and are not properly aligned on the form. When you select the buttons (being sure to select the Add button last), you can then click Format | Make Same Size | Both. Once this is done, all the buttons will take on the size of the Add button. You can then select Format | Horizontal Spacing | Make Equal, and the buttons will have the same amount of space between them. For interest’s sake, let’s look at the Windows Form Designer and examine the code that has been created behind the scenes for us. private void InitializeComponent() { this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabStudents = new System.Windows.Forms.TabPage(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.buttonAdd = new System.Windows.Forms.Button(); this.buttonEdit = new System.Windows.Forms.Button(); this.buttonDelete = new System.Windows.Forms.Button(); this.tabControl1.SuspendLayout(); this.SuspendLayout(); // tabControl1 this.tabControl1.Controls.AddRange(new System.Windows.Forms.Control[] { this.tabStudents, this.tabPage2}); this.tabControl1.Location = new System.Drawing.Point(0, 24); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(544, 416); this.tabControl1.TabIndex = 0; // tabStudents this.tabStudents.Location = new System.Drawing.Point(4, 22); this.tabStudents.Name = "tabStudents"; this.tabStudents.Size = new System.Drawing.Size(536, 390); this.tabStudents.TabIndex = 0; this.tabStudents.Text = "Students"; // tabPage2 this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(568, 414); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Courses"; // buttonAdd this.buttonAdd.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.buttonAdd.Location = new System.Drawing.Point(8, 456); this.buttonAdd.Name = "buttonAdd"; this.buttonAdd.Size = new System.Drawing.Size(48, 56); this.buttonAdd.TabIndex = 1; this.buttonAdd.Text = "Add"; // buttonEdit this.buttonEdit.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.buttonEdit.Location = new System.Drawing.Point(152, 456); this.buttonEdit.Name = "buttonEdit"; this.buttonEdit.Size = new System.Drawing.Size(48, 56); this.buttonEdit.TabIndex = 2;

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 screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

7 this.buttonEdit.Text = "Edit"; // buttonDelete this.buttonDelete.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.buttonDelete.Location = new System.Drawing.Point(296, 456); this.buttonDelete.Name = "buttonDelete"; this.buttonDelete.Size = new System.Drawing.Size(48, 56); this.buttonDelete.TabIndex = 3; this.buttonDelete.Text = "Delete"; // MainForm this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(600, 525); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.buttonDelete, this.buttonAdd, this.tabControl1, this.buttonEdit}); this.Name = "MainForm"; this.Text = "Form1"; this.Load += new System.EventHandler(this.MainForm_Load); this.tabControl1.ResumeLayout(false); this.ResumeLayout(false); }

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

PART IV

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. 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.

Color profile: Generic CMYK printer profile Composite Default All-In-One 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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

8 Managing Control Focus One final area we need to investigate in this section is managing the focus of controls on your form. When a control is in the forefront of the application, it is said to have focus. This is the control that will respond when you press ENTER (although not all controls will have functionality for the ENTER key). The control with focus is usually designated by a darker border or dashes around the control. You can move the focus around the controls on a form by pressing the TAB key. EXAM TIP Microsoft considers configuring the order of tabs to be an objective of the Windows exam. The TabIndex property controls the order of tabs and is 0-based. 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 appearance, 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: 1. Select View | Tab Order. 2. Each control will have a little number in the top-left corner that specifies its current tab order. 3. Click the controls in the sequence in which you want the tab order. 4. Select View | Tab Order from the menu system. You will see the tab order on the form (shown next).

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 screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

9

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: 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.

Windows Forms Controls In Chapter 18, we introduced the various controls that are included as part of the Toolbox in the Visual Studio .NET IDE. We briefly touched on each control and its use and then went on to discuss the event model that makes up the .NET Framework. In this section, we will work with the controls you might expect to see on the exam and point out the important aspects of each. This is not meant to be a comprehensive study, by any stretch of the imagination. However, it can serve as an introduction to each control. By observing them in our application, you will be able to ascertain each control’s effectiveness for the needs of your applications. You will also familiarize yourself with some of the properties, methods, and events that are characteristic of that particular control. Before we look at these controls specifically, we should take a moment to discuss the events that are common to all controls. In Table 19-2 we present these events and a brief description of how they would be used. Keep these events in mind as we explore the various controls in the Toolbox.

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:40 PM

PART IV

this.button1.TabStop = false;

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

10 Event

Description

Click

Fires when the control is clicked. This can be the result of a mouse click or the ENTER key being pressed when the control has focus. Triggers when the mouse is double-clicked over the control. Occurs when the control is entered. Triggers when the control gets focus either by the user tabbing to the control or clicking on the control. This can also occur programmatically by setting focus on the control. Fires when a key is pressed when the control has focus. Fired after KeyDown, which occurs when a control that has focus receives a keypress. You can retrieve the character that was pressed by examining the KeyChar property of the KeyEventArgs parameter. By using the KeyPress event, you can tell whether any of the modifier keys were also pressed (CTRL, SHIFT, ALT). Occurs when a key is released. Occurs when the control is exited (or left). Occurs when the control loses focus (when the user tabs or clicks on another control). A series of events that occurs when mouse actions take place. MouseDown and MouseUp happen when the mouse button is pressed and released. By using the Button property of the MouseEventArgs parameter, you can determine which mouse button was pressed (right, left, or middle).

DoubleClick Enter OnFocus

KeyDown KeyPress

KeyUp Leave LostFocus MouseDown MouseEnter MouseHover MouseLeave MouseUp Move Validated Table 19-2

Occurs when the control is moved. Triggers when the control is finished validating. We will look at validation events later in this chapter.

Common Events for all Controls

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, Text Boxes, and Labels, Oh My! Probably the most common of all controls, buttons, text boxes, and labels are the basic user-interaction controls. By clicking a button, a user can request a certain action; by typing in the text box, a user can present data to the program; and by reading the contents of a label, a user is prompted by its value. New to the .NET Framework is the LinkLabel, which allows you to create a label that contains a hyperlink, and the RichTextBox, which permits formatted text.

Buttons Including buttons on your form allows the user to select an activity. There are three different 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 Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

11 check boxes in the “button” category, but that is because they all derive from the class ButtonBase (a subclass of Control). We will return to the discussion of radio buttons and check boxes in a few minutes, but for now, let’s concentrate on the standard Button class. To add a new button to your form, either double-click on the Button icon in the Toolbox or click it once and draw the button on your form. Once the button is added to your form, you should immediately change its name property from Buttonx, where x is the sequentially assigned number of buttons already on the form, to something meaningful like btnDelete. The following illustration demonstrates our row of buttons on the main form of our college application. You should then change the Text value from Buttonx to the visual clue for the user (that is, Delete). Double-click on the new button and you will be taken to the Click event. You can then code whatever needs to be done when the user clicks on the button.

PART IV

A .NET button can have an image added to it. Notice the graphic to the left of the “Delete” 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 installation. 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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

12 1. The Click event has been registered (or subscribed to) in the InitializeComponent() method: this.btn.Delete.Click +=new System.EventHandler(this.btnDelete_Click);

2. The event-handler stub has been created: private void btnDelete_Click (Object sender, System.EventArgs e){ }

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 warrant 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 Button 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 Computer 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 Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

13 Notice, in this example, that we have placed the buttons in a GroupBox. There are many reasons for doing this: • A GroupBox visually keeps all the radio buttons together. • When you don’t use a GroupBox, only one radio button can be selected per form. To have multiple areas of selection, you need multiple group boxes. • When you move the GroupBox, the buttons inside move with it, keeping the controls together. Table 19-3 identifies some of the more common properties and events for a RadioButton. EXAM TIP A GroupBox is very similar to the Panel control—both act as containers for other controls. The difference between the two is that a GroupBox has a caption on it and a Panel can have scroll bars.

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 Windows 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

PART IV

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 application in the Visual Designer. The difference between a check box and a radio button has 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.

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

14 Properties

Name

Description

Appearance

A RadioButton can be displayed either as seen in the preceding illustration or as a simple click button. The RadioButton will automatically change its state (on or off) when it is clicked. You can test whether the button has been selected by determining the True/False value of Checked. This event occurs when the Appearance property value changes. This event is fired when the Checked property value changes. When a radio button is clicked, this event happens twice—once to the button that was previously checked and once to the button that is now checked. When a radio button is selected, the Click event fires once.

AutoCheck Checked Events

AppearanceChanged CheckedChanged

Click Table 19-3

Properties and Events of a RadioButton

two options—selected or unselected. In order to add in the indeterminate feature, you must do two things: • Set the CheckState property to Indeterminate. • Set the ThreeState property to True. 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. private void btnToggle_Click (object sender, System.EventArgs e) { if ((cbTest1.CheckState == CheckState.Checked) || (cbTest1.CheckState == CheckState.Unchecked)) cbTest1.CheckState = CheckState.Indeterminate; if (cbTest1.CheckState == CheckState.Indeterminate) cbTest1.CheckState = CheckState.Checked; }

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 Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

15 formatted text in a text box. We will also discover later in this chapter that we can use the text boxes to force the user to enter a certain kind of data. For example, you may want to ensure that only numeric values are entered into the text box—in the “Validating User Input” section of this chapter, we will look at this capability in detail. Let’s look at some of the more interesting properties of the TextBox class: • CharacterCasing Allows you to set whether the text that is entered is in lowercase, uppercase, or remains the way it was typed. The default value is Normal. • MaxLength Allows you to set the maximum number of characters to be entered into the TextBox. By default, the only practical limit is the amount of memory in the host machine. • Multiline

Allows the control to display multiple lines of text.

• ScrollBars Allows you to specify that the control will show the scroll bars if the control is also set to display multiple lines of text.

• 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 formatted 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 illustrates 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

PART IV

• PasswordChar Replaces the typed characters with a special password character. For example, most password boxes display asterisks (*) over the typed password for security reasons.

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

16

Figure 19-1

Example of a RichTextBox control

that will set a selected area of text to bold. The code to implement this in the Button Click event is as follows: private void btnSetBold_Click(object sender, System.EventArgs e) { Font oldFont; Font myFont; oldFont = this.rtfTest1.SelectionFont; myFont = new Font (oldFont, FontStyle.Bold); this.rtfTest1.SelectionFont = myFont; this.rtfTest1.Focus(); }

When the button is clicked, whatever text is selected is converted to bold. In our example, 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 properties 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 Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

17 Labels This is probably one of the most used controls in the Windows application environment. Using a label allows you to provide information to the user. There are two types of label controls that can be added to a Windows form: Label is the standard label, and LinkLabel allows you to create a hyperlink label. We have modified our form and added a label (see the next illustration) encouraging students to click on the hyperlink to reach Microsoft’s web site.

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: this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0,20); this.linkLabel1.Location = new System.Drawing.Point (240, 344); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Text = "Microsoft\'s Web Site"; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler (this.linkLabel1_LinkClicked);

In the linkLabel1_LinkClicked event, we add the following code: private void linkLabel1_LinkClicked (object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { // find out which link was clicked linkLabel1.Links[linkLabel1.Links.IndexOf (e.Link)].Visited = true; System.Diagnostics.Process.Start ("http://www.microsoft.com"); }

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

18 Now when you click on the hyperlink in the LinkLabel control, you will be taken to a new instance of Microsoft Internet Explorer, and the web site for Microsoft will open.

List Boxes, Combo Boxes, Checked List Boxes, and Such In order to provide users with a list of options from which to choose, we utilize the ListBox and its various adaptations—ComboBox and CheckedListBox. Look at Figure 19-2 to see the difference between the three of them. The ListBox allows a list of data to be presented to the user with a scrollbar on the right side for scrolling through the list. The ComboBox presents a drop-down list of data to the user. Notice that in our example the data is sorted—this is accomplished by setting the Sorted property to True. Other properties that can be set on the ComboBox include the following: • MaxDropDownItems controls the number of items shown in the drop-down list. • DropDownStyle can be set to Simple, DropDown, or DropDownList (see Figure 19-3).

Figure 19-2

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:42 PM

Using ListBox, ComboBox, and CheckedListBox controls

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

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: • MultiColumn

Permits multiple columns of data to be displayed.

• SelectionMode Allows you to set the maximum number of items that can be selected at a time. • SelectedIndex Specifies the first selected item by item (or index) number (if no item is selected, this value is 1). • Items Contains the data that is displayed in the list. Items is a collection. The Count property will return the number of items in the list. The Add property will add items to the list at run time, and the Remove property will

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

20 delete items at run time. Items.Addrange allows you to add multiple items to the list box. 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 database 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 yourself 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 Collection 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 Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

21 For interest’s sake, here are a few tidbits that help when using a TabControl. • 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();

To add a new TabPage dynamically to your TabControl, follow the example of this code segment:

Status Bars The StatusBar control is usually used to display information to the user in an unobtrusive 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 collection, 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: this.sbMyStatusBar.Panels[2].Text = "Here is the changed text for the third panel.";

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

PART IV

TabPage tpStudentMarks = new TabPage(); tpStudentMarks.Text = "Student Marks"; tpStudentMarks.Size = new System.Drawing.Size (536, 398); // 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);

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

22 Toolbars The ToolBar control is an area on your window where you can set shortcut buttons for different commands (typically menu options). Figure 19-4 shows a ToolBar control on our college application. We have not looked at creating menus yet, so you will see silly buttons on this toolbar. When we work on menus later in this chapter, you will see the true use of a toolbar. Once the ToolBar control is added to your form, you can add buttons to it by clicking on the Buttons property and selecting the collection. Use the ToolBarButton Collection Editor in the same fashion as the editors for the StatusBar and the TabPage. In Figure 19-4, you will notice that there are really four buttons on the toolbar, and each one has a different Style property: • 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.

Figure 19-4

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:43 PM

Using a ToolBar control

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

23 • The last button (really the third button) is the one between the American flag and the Swedish flag. It has the style of Separator and acts as a separation point between toolbar buttons. 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 window (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 particular 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.

Types of Dialog Boxes There are many types of dialog boxes available for immediate use, and you can also create your own. In this section, we will explore the prebuilt dialog boxes. Table 19-4 lists the different types and describes their purposes. The MessageBox The MessageBox control allows the developer to display an informational message and wait for the response. In Figure 19-5, we have adjusted our Courses tab to include a course-selection list box. When the user clicks on any of the items in the list, a message box is displayed as shown in the figure. The hardest part to creating a message box is determining its look. We used the following code line in the SelectedIndexChanged event of the list box, meaning that the box will be displayed as a result of any click within the list box: MessageBox.Show (this, "Sorry, this course if full!", "Course Selection", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:43 PM

PART IV

Dialog Boxes Using a dialog box is a great way to interact with the user. You may want to simply present 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 window 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.

Color profile: Generic CMYK printer profile Composite Default All-In-One 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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

24 Dialog Box

Purpose

MessageBox

Creates a simple message for the user. Displays a question or message to the user and waits for their response. Allows the user to select colors for the application. They can choose from a list of colors or create a custom color. Allows the user to select a font, the style of the font, and its size, from the fonts that are installed on the computer. Allows the user to navigate the file system and choose a particular file to open. This is the same dialog box you see when you choose File | Open from a typical Windows menu system. Allows the developer to present the standard printer-related dialog boxes. PageSetupDialog presents the dialog box used to specify printer settings. PrintDialog lets the user select a printer and choose the pages to print (exactly as if you chose File | Print from a standard Windows application menu. The PrintPreviewDialog control presents the document on screen as it will look printed.

ColorDialog FontDialog OpenFileDialog

PageSetupDialog PrintDialog PrintPreviewDialog

Table 19-4

Figure 19-5

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:43 PM

.NET Dialog Box Controls

Using a MessageBox control

Color profile: Generic CMYK printer profile Composite Default screen All-In-One 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

Chapter 19: User-Interface Components

25 Dialog Box

Purpose

SaveFileDialog

Allows the user to choose the location for a saved file. This is the dialog box you will see if you select File | Save from a standard Windows application menu.

Table 19-5

.NET Dialog Box Controls (continued)

As you can see, there are enumerations that help make the appearance choices for the message box. These include the following: • MessageBoxButtons Select OK, OKCancel, AbortRetryIgnore, RetryCancel, YesNo, or YesNoCancel as the buttons to include on the MessageBox. • MessageBoxDefaultButton Select Button1, Button2, or Button3 as the button to respond to the ENTER key. • MessageBoxIcon In our example, we used the information icon, but you can select from a list of icon choices, including Error, Stop, Warning, and so on.

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 }

The DialogResult enumeration contains named constants (Abort, Cancel, Ignore, OK, Yes, and so on) for comparing against the results of the user clicking one of the option buttons. Using Dialog Boxes from the CommonDialog Class Aside from the Message Box, all the dialog boxes listed in Table 19-4 are derived from the CommonDialog class, and they all work in approximately the same manner. You use the inherited ShowDialog() method to display the dialog box from your application and the DialogResult class to retrieve the user interaction with the dialog box. As an example, we will use the File | Save dialog box (SaveFileDialog), as shown in Figure 19-6.

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:44 PM

PART IV

The Show() method of the MessageBox class is overloaded so that you can display the default message box with only a message and the OK button, or you can create an elaborate box using all of the options.

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

26

Figure 19-6

The SaveFileDialog dialog box

Use the following steps to recreate this section of the application: 1. Add an instance of the SaveFileDialog control to your application. The instance will show at the bottom of the white area in the Visual Designer. 2. In the Click event of the Save button, add this code: // use the instance of the SaveFileDialog control to set initial properties saveFileDialog1.InitialDirectory = "c:\\C Progs\\Ch25"; saveFileDialog1.Filter = "C# source files | *.cs"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { // write your code here }

3. Notice that you can set the initial directory that the Open File dialog box will display. Use the double-slash escape sequence (\\) to set the directory path. You can also set a filter—in our case, we only want to see C# source files. 4. Run the application and click on the button. 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 example, 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 Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

27 By making proper use of dialog boxes, you can ensure that your application will retain some consistency between programs. You also save yourself a lot of valuable time by not reinventing the wheel (or, in this case, the dialog box).

Working with Controls at Run Time Although it is very easy to add controls to your application at design time by making use of the Windows Forms Designer, it is imperative to understand how to add controls at run time. Very often, you will need to create a control on the fly, in response to the circumstances during the running of your application. We will look at the ControlsCollection and talk about the Controls property, which let you do this. 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.

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: • You can add or remove controls from the collection. • You can iterate through the collection by using the GetEnumerator() method. • By calling the Contains() method, you can check whether a particular control is part of the collection. • You can use the Count property to return the number of controls in the collection. 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

PART IV

The Collection Object

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

28 Any control that acts as a container has the Controls collection. If we wanted to clear the controls from a TabPage, we would code this line: tabPage1.Controls.Clear();

Adding a Control at Run Time We are able to create a customized version of our application by allowing users to add and remove controls at run time. By adding the following code section to our college application, teachers can access a few more controls than students can. In Figure 19-7, we have added a button that, when clicked, displays a text box on the tab page asking for a password. The text box is not part of the form until someone clicks on the If You Are a

Figure 19-7

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:44 PM

Adding a control at run time

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

29 Teacher, Click Here button. Once the password is validated, we can then add more functionality via extra controls for a teacher. The new code looks like this: private void btnTeacher_Click (object sender, System.EventArgs e) { TextBox t = new TextBox(); t.Text = "Enter your password "; t.Width = 200; t.Left = 250; t.Top = 320; tabCourses.Controls.Add (t); }

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 programmer will work. Experiment with each one of them—Microsoft expects you to have a full understanding of their functionality.

Creating a Main Menu To our college application, we have added a menu system that contains the standard menus (File, Edit, and Help) as well as an application-specific menu, Students (see Figure 19-8). Creating a menu system from the Visual Designer is very simple. Building a menu is as easy as adding an instance of the MainMenu control to the application. Like the ImageList control, it is not added directly to the form, but rather sits at the bottom of the IDE screen. Once an instance of the control becomes part of your application, you will be presented with the first menu item and a prompt to “Type here.” We have added items down to the Exit on the File menu and across to the Help menu, as is shown in Figure 19-8. The menu control leaves open space for us to add to the menu system at any time.

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:44 PM

PART IV

Working with Menus 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.

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

30 Some special considerations should be taken into account when working with menus: • 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.

Figure 19-8

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:45 PM

Our college application with menus

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

31

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 • Enabled

Specifies the menu item as the default.

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.

Looking at the Code of a Main Menu Although the convenience of the Visual Designer abstracts a lot of the coding from us, it is important that we examine the “behind the scenes” coding. We can’t just ignore the programming part of this assignment. The following code segments show you just how

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

32 much work is done for you by the Visual Designer. By acquainting yourself with the coding of menus, you will be able to dynamically add menus to your application. Each object is declared in the declaration section of the Form class: private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; // and so on for each menu item // Please be sure to use more meaningful names in your applications.

The next step is to construct each of these objects. This happens in the method: InitializeComponent(). this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); // and so on for each menu item // did we mention that the names should be changed?

The properties are then set for each object: // this is the parent object mainMenu1 // the code below identifies the top-level menu items that belong to this parent this.mainMenu1.MenuItems.AddRange (new System.Windows.Forms.MenuItem[] { this.menuItem1, this.menuItem10, this.menuItem18, this.menuItem24)}; // menuItem1 becomes the parent for all of the menu items under it this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange (new System.Windows.Forms.MenuItem[] { this.menuItem2, this.menuItem3, // etc for each menu item that is a child of menuItem1 // and so on until we reach the properties of each individual child menu item this.menuItem1.Text = "File"; // etc for each one

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;

Handling Menu Events When you double-click on the menu item that you have added to your form, you will be taken to the code view window and placed inside the menuItemxx_Click event. The Visual Designer will add the necessary subscription to the event handler, as follows: this.menuItemxx.Click += new System.EventHandler (this.menuItemxx_Click);

You could also change this subscription as follows: this.menuItemxx.Click += new System.EventHandler (<methodname>);

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 screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

33 In this case, the <methodname> is a method call instead of a reference to a click event. There are many reasons to do it this way, but perhaps the most compelling reason is that there may be different ways of calling that menu item, and they can all make the call to <methodname>. For example, you may have a toolbar on your form that has a button that will produce the same effect as clicking on a particular menu item. Both the menu item and the toolbar button will call the same method.

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

Figure 19-10

A context menu attached to a text box

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

34

Figure 19-11

Using a context menu

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. MenuItem menuNewItem = new MenuItem(); menuNewItem.Text = "&Window"; contextMenu1.MenuItems.Add (menuNewItem);

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.

Validating User Input Although good form design is very important to the development of Windows applications, it is just as important to pay attention to the data that the user is entering. There

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 screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

35 are many techniques for validating the information supplied by users of your application. We will discuss two of the methods: • Using the Validating event of a control • Using the ErrorProvider control 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 shortcut, 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

Figure 19-12

Setting up the validating event

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

36 A list of that control’s events is presented (see Figure 19-12) and by double-clicking on the event, the code is added to your program. We double-clicked on the Validating event, and the Visual Designer added the following code: this.textBox1.Validating += new System.ComponentModel.CancelEventHandler ( this.textBox1_Validating);

A Validating event method is also added to the code: private void textBox1_Validating (object sender, System.ComponentModel.CancelEventArgs e) { // place your validation code here }

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!"); } }

EXAM TIP You can set the CausesValidation property of a control to False if you do not want the Validation event to fire when exiting the control.

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

P:\010Comp\All-in-1\443-6\ch19.vp Friday, August 23, 2002 5:02:46 PM

Move your mouse over the question mark to see the error message.

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

37

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 questions, 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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

38 Test Questions 1. If you want to ask the user to select between two or more mutually exclusive options, you would employ which of the following controls? A. TabControl B. Button C. RadioButton D. CheckBox 2. The following piece of code is intended to create a new TabPage in a TabControl. What will happen when you try to run this code? TabPage tpMyNewTabPage = new TabPage(); tpMyNewTabPage.Caption = "Add Students"; tpMyNewTabPage.Size = new System.Drawing.Size (536, 398); Button b = new Button(); tpMyNewTabPage.Controls.Add (b);

A. The program compiles and executes properly. B. The program compiles and causes a runtime error. C. The program does not compile because it is unable to add the button. D. The program does not compile because of a syntax error. 3. The following piece of code is intended to create a new TabPage in a TabControl. What will happen when you try to run this code? TabPage tpMyNewTabPage = new TabPage(); tpMyNewTabPage.Text = "Add Students"; tpMyNewTabPage.Size = new System.Drawing.Size (536, 398); Button b = new Button(); tpMyNewTabPage.Controls.Add (b);

A. The program compiles and executes properly. B. The program compiles but the tab page does not show. C. The program compiles and causes a runtime error. D. The program does not compile because of a syntax error. 4. You want to validate the user input that is retrieved in a text box. Which control will assist you in displaying the error message without moving off the form? A. RichTextBox B. NotifyIcon C. HelpProvider D. ErrorProvider

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 screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

39 5. You want to validate the user input that is retrieved in a text box. Which event will assist you in the validation of the data? A. UponValidation B. Validation C. Validating D. OnValidation 6. Which of the following lines of code will produce a message box for the user? A. MessageDialogBox.Show ("This is your message"); B. MessageDialogBox.Show ("Message", "This is your message"); C. MessageBox.Show ("This is your message); D. MessageBox.Show ("Message", "This is your message"); 7. To dynamically add a context menu to your application, which section of code should be used? A. MenuItem m = new MenuItem(); contextMenu1.MenuItems.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

PART IV

B. MenuItem m = new MenuItem(); contextMenu1.MenuItem.Add (m);

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

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

40 10. What is wrong with the following piece of code? Assume no other code has been written and you are creating the status bar dynamically. this.sbMyStatusBar.Panels[1].Text = "Panel 1"; this.sbMyStatusBar.Panels[2].Text = "Panel 2"; this.sbMyStatusBar.Panels[3].Text = "Panel 3";

A. Nothing is wrong with the code. B. It will cause a runtime error. C. There will be a syntax error found. D. The Text property is incorrect for a StatusBar. 11. Which line of code must be added in order to show a StatusBar? A. sbMyStatusBar.Show(); B. sbMyStatusBar.Display(); C. sbMyStatusBar.Show = true; D. sbMyStatusBar.Display = true; 12. Which line of code will set the Link data for a LinkLabel? A. this.linkLabel1.Text = "http:\\www.microsoft.com"; B. this.linkLabel1.Link = "http://www.microsoft.com"; C. this.linkLabel1.HyperLink = "http://www.microsoft.com'; D. None of the above. 13. Which segment of code will set the selected text in a RichTextBox to bold? A. myFont = new Font (oldFont, Font.Bold = Bold); this.rtfTest1.SelectionFont = myFont; B. myFont = new Font (oldFont, FontStyle.Bold); this.rtfTest1.SelectionFont = myFont; C. myFont = new Font (oldFont, FontStyle.Bold); this.rtfTest1.SelectedText = myFont; D. myFont = new Font (oldFont, Font.Bold); this.rtfTest1.SelectedText = myFont; 14. Which property will allow the user to enter more than one line in a text box? A. MaxLines B. MultipleLines C. MultiLines D. MultiLine

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 screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

19

Chapter 19: User-Interface Components

41 15. Which control would you use to group a lot of controls together? A. GroupControl B. GroupBox C. FrameControl D. FrameBox

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. 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

PART IV

7. A. The collection is called MenuItems, and you must create MenuItem objects.

Related Documents

Ch19
November 2019 16
Ch19
November 2019 17
Ch19
April 2020 10
Ch19
November 2019 15
Ch19
June 2020 10
Fps > Ch19
July 2020 4