Lesson 3: Using Controls and Components

Lesson 3: Using Controls and Components

Controls are the second element of the visual interface. These graphical tools, also known as Windows Forms controls, are used to create or enhance the functionality of an application. Tools are added to the form from the Visual Studio Toolbox. Some, such as Button and TextBox, are designed to receive user input and carry out basic tasks associated with user interaction. Others are specialized components designed to manage complex interactions with other parts of the application. Components are similar to controls in that they are existing units of code that encapsulate specific functionality. The main difference between components and controls is that controls have a visual representation, whereas components do not. This lesson provides information on using controls and components when building a user interface.

After this lesson, you will be able to

  • Define the role of controls in your application

  • Explain the difference between controls and components

  • Explain how to set the control tab order

  • Describe which controls can contain other controls and how they are used

  • Describe docking and anchoring, and explain their use with controls

  • Explain how to dynamically add controls to your form

  • Describe the process for adding controls to the Toolbox

  • Describe how to create event handlers for controls

  • Explain what an extender is and how to use one

Estimated lesson time: 45 minutes

Working with Controls

The Visual Studio Toolbox contains a variety of preset controls that you can use to develop your applications. Controls are hosted in forms and implement most of the actual functionality in the user interface. Take the Button control, for example. It can be placed on a form and will be displayed, usually with a title that provides some kind of information as to its function. When the user clicks the button with the mouse, an event handler responds to the click and causes code to execute. Other controls, such as the Label control and PictureBox control, are primarily used to display data to the user. Controls such as TextBox and ListBox serve a dual purpose: both display information and allow the user to input information.

You can add controls to the forms in your application by using the designer. The designer displays the form you are composing in a graphical state, similar to how the form will look at run time. The Toolbox allows you to select a control with the mouse and add it to the form surface in the designer. All the code associated with the control is also added to your application. You can reposition controls by clicking and dragging them with the mouse. You can resize most controls by grabbing their edge with the mouse and adjusting them as desired. Because an in-depth discussion of the different controls and their functionality is beyond the scope of this book, you should familiarize yourself with the controls in the Toolbox and how they work.

To add a control to your application

  1. From the Toolbox, select the control you want to add.

  2. Click the form in the location where you want the control to appear. While holding down the left mouse button, draw the control to the size you want it to be on the form.

    Alternatively, you can drag the control from the Toolbox onto the form, or double-click the desired control in the Toolbox. The control will be added to the form with default values for size and position, if appropriate.

  3. Use the mouse to set the size and position of the control as desired. You can also use the arrow keys to position the control.

The Properties window displays the properties of the selected control and allows you to edit them. Setting a property during the design stage creates its default value, which can still be changed in the course of code execution. Moving the control on the form in the designer sets the position properties of the control. Although you can accomplish these same tasks in code, the designer allows you to rapidly set control start-up properties rather than spend valuable development time hand- coding values.

To edit properties of a control

  1. Right-click a control, and select Properties. You can also left-click the control and press F4, or choose Properties from the View menu.

  2. Edit the value in the appropriate property box.

To edit properties for multiple controls

  1. Click and drag the mouse over the controls to select the controls you want to edit.

    Alternatively, hold down the Ctrl key and click the controls you want to edit. The Properties window displays the properties that are common to all controls selected.

  2. Edit the value in the appropriate property box.

Components are also in the Toolbox. Components are similar to controls in that they are pre-assembled units of functionality that you can incorporate into your application. The primary difference between controls and components is that components are not visible in the user interface. An example of a component is the Timer, which raises an event at a specified interval. Because they have no visual interface, components are not added to the form when you add them to your application in the designer. Instead, they are added to the component tray, a graphical region near the bottom of the designer that allows you to manipulate the properties of your application s non-visual components. Components are added to an application in the same way controls are added; likewise, the Properties window is used to edit component properties.

Setting the Control Tab Order

The users of your application can use the Tab key to quickly move the focus from one control to another. The tab order sets the order in which controls on the form receive the focus. Tab order is specified by the TabIndex property. To change the order in which a control receives the focus, simply set the TabIndex property to a different value. Lower values receive the focus first and proceed numerically through higher values. In the event of a tie between TabIndex values, the focus first goes to the control closest to the front of the form. You can bring a control to the front or send it to the back of the form by right-clicking it and choosing Bring To Front or Send To Back, respectively.

Visual Studio contains a tool for setting the tab order. Under the View menu, choose Tab Order. A box containing a number appears inside each control on the designer. To set the tab order, all you have to do is click the controls in the order that you want them to receive the focus.

NOTE
Some controls, such as PictureBox, cannot receive the focus and thus do not have a TabIndex property.

To set the tab order using the TabIndex property

  1. In the designer, select each control capable of receiving the focus.

  2. In the Properties window, set the TabIndex property to an appropriate value. The focus passes from control to control in the order of lowest to highest value.

To set the tab order with Visual Studio .NET

  1. From the View menu, choose Tab Order. Boxes containing the current tab order appear in each control.

  2. Click each control in the desired tab order.

  3. From the View menu, choose Tab Order again to resume editing.

Controls That Can Contain Other Controls

Some controls, known as container controls, allow you to place other controls inside of them. Container controls include Panel, GroupBox, and TabControl. You can use these controls to logically organize groups of controls or a form. For example, you might group a set of related radio buttons in a GroupBox control. Using these controls allows logical groupings of controls that you can manipulate programmatically. These controls also help to create a sense of style or information flow in your user interface, and they provide visual cues to the user.

NOTE
A container control acts as a host for other controls but is independent of those controls. Contrast this with user controls, which can bind multiple controls together into a single interdependent unit. User controls will be discussed in detail in Chapter 7.

When a control contains another control, changes to properties of the container control can affect the contained controls. For example, if the Enabled property of a GroupBox control is set to false, all the controls contained within this control are disabled. Likewise, changes to controls related to the user interface, such as BackColor, ForeColor, Visible, and Font, are also applied to contained controls. This allows you to easily create a consistent look for your user interface. The Anchor and Dock properties of contained controls also function relative to the containing control. These properties are discussed further in the section Docking and Anchoring Controls later in this lesson.

NOTE
Changes in the visual properties of a container control will change the corresponding property in contained controls, but you can still manually change any of these properties on a contained control. If the container control is disabled, however, there is no way to enable a contained control short of re-enabling the containing control.

Using the GroupBox and Panel Controls

The GroupBox and Panel controls are similar. Both provide a logical and physical grouping of controls. These controls can be thought of as physical subdivisions of a form. Changes in the properties of a Panel or GroupBox affect all the controls contained within. Controls contained within a Panel or GroupBox can be moved and repositioned as a single unit during the design stage. At run time, you can disable the entire group by setting the Enabled property of the containing control to false.

The GroupBox control provides a caption for labeling the group of controls within it. You can set this caption using the Text property. The Panel control is a scrollable container, but it does not provide a caption. By setting the AutoScroll property to true, you enable scroll bars within the panel.

Using the TabControl Control

The TabControl control is a way to group controls on a set of tabs, rather like files in a filing cabinet or dividers in a notebook. The TabControl is a host for a number of TabPages that host other controls. An example of the TabControl might be property pages for an application, with each tab representing properties related to a specific component of the application.

The most important property of TabControl is TabPages. The TabPages property is a collection of TabPage controls, each with its own set of properties. A collection is a logical organization of objects similar to an array. Collections are discussed in detail in Chapter 3. You can access each TabPage by clicking the tab that represents it, as shown in Figure 2.6.

figure 2-6 tabpages in a tabcontrol.

Figure 2-6. TabPages in a TabControl.

Individual TabPages are similar to Panel controls. They provide a scrollable form subdivision that can host a set of other controls. By setting the Autoscroll property to true, you enable the scroll bars for each TabPage.

TabPages are added to the TabControl by setting the TabPages property. When the TabPages property is selected in the designer, the TabPage collection editor appears. From this window, you can add TabPages to your control and set the properties for each. Once added, you can click the appropriate tab in the designer and add controls to the design surface represented by the TabPage. At run time, the user is able to move between different tab pages by clicking the appropriate tabs.

Docking and Anchoring Controls

The Anchor and Dock properties of a control dictate how it behaves inside its form or parent control. The Anchor property allows you to define a constant distance between a control and one or more edges of a form. Thus, if a user resizes a form at run time, the control will always maintain a specific distance from the edges indicated. The Dock property allows you to attach a control to an edge of the form or to completely fill the form. A docked control will resize itself when the form is resized.

Using the Anchor Property

You can set the Anchor property for any control in the same way you set any other property. In the Properties window, choose Anchor. When the drop-down button is clicked, you are presented with a visual interface to help choose anchoring properties, as shown in Figure 2.7.

figure 2-7 choosing the anchor property.

Figure 2-7. Choosing the Anchor property.

You can use the window shown in Figure 2.7 to choose the edges to which you want to anchor your control. The default value for this property is Top, Left, which causes the control to maintain a constant distance between the form s top and left edges. Because forms are resized from the lower-right corner, the net result of this setting is a control that always maintains its position.

In this exercise, you add a button to a form and set the Anchor property to a variety of values to observe the effect the Anchor property has on control location and sizing.

To demonstrate the Anchor property

  1. In Visual Studio, create a new Windows Forms project.

  2. In the designer, add a button to the form.

  3. Click the button once, and in the Properties window, select the Anchor property.

    The Anchor property window appears. Note that the top and left bars are darkened, indicating that the control is currently anchored to the top and left edges of the form.

  4. In the designer, resize the window by grabbing the lower-right corner with the mouse and dragging. Note that the button maintains its position relative to the top and left edges.

  5. In the Anchor property window, click both bars. The button is no longer anchored.

  6. In the designer, resize the form again. Now the button floats on the screen in response to resizing.

    If a control has an Anchor property setting of None, it will maintain a proportional distance between the edges instead of an absolute distance.

  7. Next set the Anchor property to Top, and resize the form.

    Although the button maintains a constant distance from the top edge, it floats relative to the left and right edges.

  8. In the anchor designer window, click the bottom bar, setting the Anchor property to Top, Bottom.

  9. Resize the window once more. The button still floats relative to the left and right edges, but now it maintains a constant distance between the top and bottom edges. To do this, it must resize itself.

    The Anchor property allows you to manage how controls respond to resizing the form. You can allow controls to remain fixed in the form by anchoring them to the top and left edges, cause them to stretch when resized by anchoring them to opposite edges, or allow them to float freely by releasing the anchor. Use of the Anchor property allows you to implement a variety of resize and relocation behaviors.

Using the Dock Property

Docking refers to attaching your control to the edge of a parent control. The parent control is usually a form, but it can include other container controls such as the Panel or Tab control. An example of a docked control might be a menu bar at the top of a form.

You can set the Dock property of a control at design time in the Properties window. After selecting the Dock property, a graphic interface appears that allows you to choose the docking characteristics of your control. The interface is shown in Figure 2.8.

figure 2-8 setting the dock property.

Figure 2-8. Setting the Dock property.

To set the Dock property, simply click on the section of the interface that corresponds to where you want your control to dock. For example, if you want your control to dock at the top of the form, click the bar at the top of the interface. To release docking, choose None. Clicking the center square of the Dock property interface causes the control to fill the form in which it lives. If you set docking for a control, the Anchor property is set to Top, Left.

To set docking characteristics for your control

  1. In the Properties window, choose the Dock property. The Dock property visual interface appears.

  2. Click the section of the interface you want to use as your dock setting.

Using the Controls Collection

Every container control, including forms, exposes a collection of all the controls it contains. This collection is called the controls collection. The controls collection exposes a Count property, which returns the number of items contained within it, and an Item property, which returns a specific item. The controls collection also has member methods that can be used to add and remove controls to and from the collection.

In Visual Basic .NET, the Item property returns a specific control based on the Index of the item. In Visual C#, the property indexer is used. For example:

Visual Basic .NET

' Assumes the presence of a form called myForm Dim aControl As Control aControl = myForm.Controls.Item(3)

Visual C#

// Assumes the presence of a form called myForm Control aControl; aControl = myForm.Controls[3]; 

NOTE
In Visual Basic .NET, because the Item property is the default property of the controls collection, you can omit the word Item when using it. Thus, the preceding example is equivalent to the following code.

Visual Basic .NET

Dim aControl As Control aControl = myForm.Controls(3)

You can dynamically add and remove controls to and from the controls collection using the Add and Remove methods. The following example creates a label control and adds it to the controls collection of a form named myForm:

Visual Basic .NET

Dim aLabel As New Label() aLabel.Text = "This label is being added dynamically" myForm.Controls.Add(aLabel)

Visual C#

Label aLabel = new Label(); aLabel.Text = "This label is being added dynamically"; myForm.Controls.Add(aLabel);

Likewise, the Remove method removes a control from a controls collection. The RemoveAt method is useful for removing a control located at a specific index in the collection. Examples follow:

Visual Basic .NET

myForm.Controls.Remove(Button1) myForm.Controls.RemoveAt(3)

Visual C#

myForm.Controls.Remove(Button1); myForm.Controls.RemoveAt(3);

Similar syntax is used to add and remove controls to and from the controls collection of a container control, such as a Panel or a GroupBox control. The following example demonstrates how to dynamically add a control to a TabPage in a TabControl:

Visual Basic .NET

' This example assumes the existence of a control called ' myTabControl Dim aButton As New Button() ' This line adds a new button to the tab page located at index 1 ' of the TabPages collection in the TabControl myTabControl.TabPages(1).Controls.Add(aButton)

Visual C#

// This example assumes the existence of a control called // myTabControl Button aButton = new Button(); // This line adds a new button to the tab page located at index 1 // of the TabPages collection in the TabControl myTabControl.TabPages[1].Controls.Add(aButton);

Adding Controls to the Toolbox

You are not limited to the controls provided by the .NET Framework base class library. Third-party developers might supply additional controls for you to use in your development, or you might create your own controls, as you will see in Chapter 7. These controls can be added to the Toolbox for use in the development environment.

To add a control to the Toolbox

  1. Choose the Toolbox tab to which you want to add a control. The tab opens.

  2. Right-click the Toolbox within that tab area, and choose Customize Toolbox.

    The Customize Toolbox window appears. The Customize Toolbox window displays all components registered on your system. These components are divided between two tabs a tab that lists all the available .NET components and a tab that lists earlier COM components.

    NOTE
    If the Toolbox is not visible, choose Toolbox from the View menu to make it appear.

  3. If the control you want to add is already registered on the system, select it from the appropriate list and click OK.

  4. The control is added to the Toolbox.

  5. If the control you want to add is on a floppy disk or in another location, click Browse and browse to the directory location of the file.

  6. Select the file, and click OK.

    The control is added to the Toolbox. Note that to add a control to the Toolbox, it must be recognizable as an ActiveX Control, COM component, or .NET assembly.

Creating Event Handlers for Controls

Events represent incidents that happen in the course of program execution. Each control can raise a variety of events that correspond to user interaction. A familiar example is clicking a button. When a button is clicked, the application raises the Button.Click event and determines if any methods handle that event. If one or more methods are found to handle that event, those methods are executed. These methods are called event handlers.

You can create event handlers to allow your application to respond to user input. Every control has a default event, which represents the event that a control is most likely to raise. For example, the Button default event is Click, and the Checkbox default event is CheckChanged. You can easily create an event handler for the default event of a control by double-clicking the control in the designer.

To create an event handler for your control s default event

  1. In the designer, double-click the control. The code window opens to a blank event handler for the control s default event.

  2. Place the appropriate code in the event handler.

Controls have many other events that can be used for a variety of purposes. You might use the MouseOver event, for example, to change the control text when the mouse passes over it. The Validate and Validating events provide support for validating user input, as is discussed in Lesson 5 of this chapter. Other events can be used to enhance the user interface and provide information to the user. The names of these events indicate when they are raised. You can write event handlers for events in the same manner in which you write event handlers for form events.

To create an event handler with Visual Basic .NET

  1. In the Code Editor view, choose the appropriate control from the Class Name drop-down menu at the top of the code editor.

  2. In the Method Name drop-down menu, choose the event for which you want to write code.

    A default event handler is added to your code editor. You can now write code in this method, which will execute when this event is raised.

To create an event handler with Visual C#

  1. In Design view, use the mouse to select the control for which you want to create an event handler.

  2. In the Properties window, click the Events button. A list of available events is displayed in the Properties window.

  3. Find the event for which you want to write a handler, and double-click it.

    The Code Editor view opens to a newly created event handler for that event. You can now add code to this method, which will execute when the event is raised.

  4. Alternatively, a list of available methods will appear in a drop-down menu to the right of the event name. If you have already written an event handler, you can choose one of these methods to handle your event by selecting it from this menu.

Interacting with the Mouse

Windows Forms controls are capable of raising events that signal interaction with the mouse. Forms raise events in response to mouse clicks, for example, or when the mouse pointer simply passes over a control.

The Click and DoubleClick events are raised by controls in response to mouse clicks and double-clicks, respectively. These events are generally used to execute code based on a user choice, such as code executed when a user clicks a button. They pass an instance of the EventArgs class to their event handlers, along with a reference to the sender.

Controls are also capable of raising events in response to interaction with the mouse pointer. Depending on their actual type, controls might be capable of raising the mouse-related events detailed in Table 2.2.

Table 2-2. Mouse-Related Events

Event

Description

Type of EventArgs

MouseEnter

This event is raised when the mouse pointer enters a control.

System.EventArgs

MouseMove

This event is raised when the mouse pointer moves over a control.

System.MouseEventArgs

MouseHover

This event is raised when the mouse pointer hovers over a control.

System.EventArgs

MouseDown

This event is raised when the mouse pointer is over a control and a button is pressed.

System.MouseEventArgs

MouseWheel

This event is raised when the mouse wheel moves while the control has focus.

System.MouseEventArgs

MouseUp

This event is raised when the mouse pointer is over a control and a button is released.

System.MouseEventArgs

MouseLeave

This event is raised when the mouse pointer moves off a control.

System.EventArgs

The MouseEnter, MouseHover, and MouseLeave events represent notification that the mouse pointer is in the region of a control. They pass relatively little information to their event handlers. By contrast, the MouseMove, MouseDown, MouseWheel, and MouseUp events can be used to implement more substantial interactions between the user and the interface. Each of these events passes an instance of Mouse EventArgs to the event handler. The MouseEventArgs object contains information about the state and location of the mouse, as summarized in Table 2.3.

Table 2-3. MouseEventArgs Properties

Property

Description

Button

This property returns which, if any, mouse buttons are pressed.

Clicks

This property returns the number of times the mouse button was clicked.

Delta

This property returns the number of notches the mouse wheel rotated. This number can be either positive or negative, with positive representing forward rotation and negative representing reverse rotation. Each notch adds or subtracts 120 from the value returned.

x

This property returns the x coordinate of a mouse click.

y

This property returns the y coordinate of a mouse click.

Using Extender Provider Components

Extender providers are components that impart additional properties to controls. Take the ToolTipProvider, for example. When you place an instance of a ToolTipProvider on a form, every control on that form receives a new property. This property can be viewed and set in the Properties window, where it appears as ToolTip on n, where n is the name of the ToolTipProvider. At run time, the value of this property is displayed in a yellow box when the mouse hovers over a control.

Extender providers are usually used to provide information to the users at run time. As we ve seen, the ToolTipProvider can be used to provide Tool Tips at run time. Other extender providers include the HelpProvider and the ErrorProvider.

To use an extender provider in your project

  1. Add a component of the appropriate extender type (such as ErrorProvider) to your form. The component appears in the component tray.

  2. In the Properties window, set appropriate values for the properties provided by the extender provider.

The properties provided by extender providers actually reside in the extender providers themselves, not within the controls they extend. Thus, they are not true properties of the component and cannot be accessed in code at run time. The extender provider implements methods that can be used to access the properties it provides. By convention, these methods are always called Getn and Setn, where n is the name of the property provided. Thus, the ToolTipProvider implements methods named GetToolTip and SetToolTip, which can be used in code to access or dynamically change the value of the Tool Tip stored for a particular control. Both methods take a reference to the appropriate control as an argument, and the Set methods require a value to which the property is to be set.

To access the value of an extender property at run time

Use the Get method implemented for that property. You must supply a reference to the appropriate control.

Visual Basic .NET

' This example demonstrates how to retrieve the ToolTip for a ' Button called Button1 Dim myToolTip as String myToolTip = ToolTip1.GetToolTip(Button1)

Visual C#

// This example demonstrates how to retrieve the ToolTip for a // Button called button1 string myToolTip; myToolTip = toolTip1.GetToolTip(button1);

To set the value of an extended property at run time

Use the Set method implemented for that property. You must supply a reference to the appropriate control and a new value for that property.

Visual Basic .NET

' This example demonstrates how to set the ToolTip for a Button ' called Button1 ToolTip1.SetToolTip(Button1, "Click this button for help")

Visual C#

// This example demonstrates how to set the ToolTip for a Button // called button1 toolTip1.SetToolTip(button1, "Click this button for help");

Lesson Summary

  • You can set the tab order of the controls on your form by setting the TabIndex property or by choosing Tab Order from the View menu and clicking on your controls to set the tab order.

  • Some controls can contain other controls, which can be used to create logical and visual subdivisions of your form. Examples of controls that can contain other controls include

    • Panel

    • GroupBox

    • TabPage

  • The Dock and Anchor properties implement automatic resizing or repositioning of the controls on your form. Setting the Dock property fixes a control to an edge of your form. Setting the Anchor property specifies whether your control remains fixed, floats, or changes size in response to the form resizing.

  • You can use the controls collection of a form to dynamically add controls at run time. To add a control, you must declare and create an instance of it, and you must add it to the controls collection of the appropriate form.

  • Additional controls can be added to the Toolbox by right-clicking the appropriate section of the Toolbox and then selecting the appropriate control, or by browsing to the DLL that contains that control.

  • You can create methods that handle events for controls in the same manner you create methods that handle events for forms. These methods execute whenever the event they handle is raised.

  • Extender provider components allow you to add more properties to the controls on a form. At run time, these properties are commonly used to provide information to the user, such as a Tool Tip or Help.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net