Working with Controls

   

As discussed earlier, controls are the objects that you place on a form for users to interact with. If you've followed the examples in the previous hours, you've already added controls to a form. However, you'll be adding a lot of controls to forms, and it's important for you to understand all aspects of the process. Following the drill-down in this hour , the next two hours will teach you the ins and outs of the very cool controls provided by C#.

Adding Controls to a Form

All the controls that you can add to a form can be found in the toolbox. By default, the toolbox appears as a docked window on the left side of the design environment. This location is useful when you're only occasionally adding controls to forms. However, when doing serious form-design work, I find it best to dock the toolbox to the right side of the design environment, where it doesn't overlap so much (if at all) onto the form with which you're working.

graphics/bookpencil.gif

Remember that before you can undock a toolbar to move it to a new location, you must make sure it isn't set to Auto Hide.

The buttons on the toolbox are actually considered tabs because clicking one of them displays a specific page of controls. For most of your design, you'll use the controls on the Win Forms tab. However, as your skills progress, you may find yourself using more complex and highly specialized controls found on the other tabs.

You can add a control to a form in three ways, and you're now going to perform all three methods . Create a new Windows Application called Adding Controls. Change the name of the default form to fclsAddingControls and set its Text property to Adding Controls. Update the main entry point in the Main() function to reflect the new class name by clicking the View Code button on the Solution Explorer toolbar and then locating the reference to Form1 and replacing it with fclsAddingControls . Click Form1.cs [Design] to return to the form designer.

The easiest way to add a control to a form is to double-click the control in the toolbox. Try this now: display the toolbox and double-click the TextBox tool. C# creates a new text box in the upper-left corner of the form. Of course, you're free to move and size the text box as you please . Nevertheless, when you double-click a control in the toolbox, C# always creates the control in the upper-left corner, with the default size for the type of control you're adding.

If you want a little more authority over where the new control is placed, you can drag a control to the form. Try this now: display the toolbox and then click the Button control and drag it to the form. When the cursor is roughly where you want the button created, release the mouse button.

The last and most precise method of placing a control on a form is to "draw" the control on a form. Display the toolbox now and click the ListBox tool once to select it. Next, move the pointer to where you want the upper-left corner of the list box to appear and then click and hold the mouse button. Drag the pointer to where you want the bottom-right corner of the list box to be and release the button. The list box is created with its dimensions set to the rectangle you drew on the form. This is by far the most precise method of adding controls to a form.

graphics/bulb.gif

If you prefer to draw controls on your forms by clicking and dragging, I strongly suggest that you dock the toolbox to the right or bottom edge of the design environment or float it. The toolbox tends to interfere with drawing controls when it's docked to the left edge, because it obscures part of the form.

It's important to note that the very first item on the Windows Forms tab, titled Pointer, isn't actually a control. When the pointer item is selected, the design environment is placed in Select mode rather than in a mode to create a new control. With the pointer selected, you can select a control simply by clicking it, displaying all its properties in the Properties window. This is the default behavior of the development environment.

Manipulating Controls

Getting controls on a form is the easy part. Arranging them so that they create an intuitive and attractive interface is the challenge. Interface possibilities are nearly endless, so I can't tell you how to design any given interface. However, I can show you the techniques to move, size, and arrange controls so that they appear the way you want them to. By mastering these techniques, you'll be much faster at building interfaces, freeing your time for writing the code that makes things happen.

Using the Grid (Size and Snap)

When you first install C#, all forms appear with a grid of dots on them. When you draw or move controls on a form with a grid, the coordinates of the control automatically snap to the nearest grid coordinate. This offers some precision when adjusting the size and location of controls. In practical use, I often find the grid to be only slightly helpful because the size or location you want to specify often doesn't fit neatly with the grid locations. You can, however, control the granularity and even the visibility of the grid, and I suggest you do both.

You're now going to assign a higher level of granularity to the grid (the space between the grid points will be smaller). I find that this helps with design, without causing edges to snap to unwanted places.

To adjust the granularity of the grid on a form, you change the GridSize property (or the Width and Height subproperties of the GridSize property). Setting the Width or Height of the grid to a smaller number creates a smaller grid, which allows for finer control over sizing and placement, whereas using larger values creates a much larger grid and offers less control. With a larger grid, you'll find that edges snap to grid points much easier and at larger increments , making it impossible to fine-tune the size or position of a control. Change the GridSize property of your form now to 4,4. Notice that a lot more grid dots appear (see Figure 6.1).

Figure 6.1. Grids can be distracting.

graphics/06fig01.jpg


Try dragging the controls on your form or dragging their edges to size them. Notice that you have more control over the placement with the finer grid. Try changing the GridSize to a set of higher numbers , such as 25,25 and see what happens. When you're finished experimenting, change the GridSize values back to 4,4.

An unfortunate side effect of a smaller grid is that the grid can become quite distracting. Again, you'll decide what you like best, but I generally turn grids off on my form. You do this by setting the DrawGrid property of the form to false. Try hiding the grid of your form now.

graphics/bookpencil.gif

This property determines only whether the grid is drawn, not whether it's active; grids are always active, regardless of whether they're visible.

Selecting a Group of Controls

As your skills grow, you'll find your forms becoming increasingly complex. Some forms may contain dozens, or even hundreds, of controls. C# has a set of features that makes it easy to align groups of controls.

Create a new Windows Application titled Align Controls. Change the name of the default form to fclsAlignControls and set its Text property to Control Alignment Example. Next, update the main entry point in the Main() function to reflect the new class name by clicking the View Code button on the Solution Explorer toolbar and then locating the reference to Form1 and replacing it with fclsAlignControls . Click Form1.cs [Design] to return to the form designer.

Double-click the TextBox tool in the toolbox to add a text box to the form. Set its properties as follows :

Property Value
Name txt1
Location 20 , 20
Multiline True
Size 100 , 30
Text txt1
graphics/bookpencil.gif

If you don't set the Multiline property of a text box to true, C# ignores the Height setting (the second value of the Size property) and instead, keeps the height at the standard height for a single-line text box.

Use the same technique (double-click the TextBox item in the toolbox) to add two more text boxes to the form. Set their properties as follows:

Text Box 2:

Property Value
Name txt2
Location 90 , 80
Multiline True
Size 50 , 50
Text txt2

Text Box 3:

Property Value
Name txt3
Location 140 , 200
Multiline True
Size 100 , 60
Text txt3

Your form should now look like the one in Figure 6.2. Save the project now by clicking the Save All button on the toolbar.

Figure 6.2. It's easy to align and size controls as a group.

graphics/06fig02.jpg


By default, clicking a control on a form selects it while deselecting any controls that were previously selected. To perform actions on more than one control, you need to select a group of controls. You can do so in one of two ways, the first of which is to lasso the controls. To lasso a group of controls, you first click and drag the mouse pointer anywhere on the form. As you drag the mouse, a rectangle is drawn on the form. When you release the mouse button, all controls intersected by the rectangle become selected. Note that you don't have to completely surround a control with the lasso (also called a marquee), you only have to intersect part of the control to select it. Try this now: click somewhere in the upper-right corner of the form and drag the pointer toward the bottom of the form without releasing the button (see Figure 6.3). When the rectangle has surrounded or intersected all the controls, release the button and the controls will be selected (see Figure 6.4).

Figure 6.3. Click and drag to create a selection rectangle.

graphics/06fig03.jpg


Figure 6.4. All selected controls appear with a hatched border and sizing handles.

graphics/06fig04.jpg


When a control is selected, it has a hatched border and a number of sizing handles (the rectangles in the hatched border at the corners and midpoints of the control). Pay careful attention to the sizing handles. The control with the black-centered sizing handles is the active control in the selected group. When you use C#'s tools, such as the alignment and formatting features, to work on a group of selected controls, the values of the active control are used. For example, if you were to align the left side of the selected controls shown in Figure 6.4, each of the controls would have its Left property value set to that of the active control. When you use the lasso technique to select a group of controls, you really don't have much authority over which control C# makes the active control. In this example, you want to align all controls to the control at the top, so you'll have to use a different technique to select the controls. Deselect all the controls now by clicking anywhere on the form (other than on a control).

graphics/bookpencil.gif

When the sizing handle of an active control is colored white, you can click and drag the handle to alter the size of the control. Not all sizing handles are movable at all times. For example, before you set the Multiline property of a text box to true, C# won't allow you to change the height of the text box, so only the sizing handles at the left and right edges are movable and therefore are colored white.

The second technique for selecting multiple controls is to use the Shift or Ctrl key; this method is much like selecting multiple files in Windows Explorer. Click the bottom control (txt3) now to select it. Notice that its sizing handles are outlined in black; because it's the only control selected, it's automatically made the active control. Now hold down the Shift key and click the center control (txt2); txt2 and txt3 are now selected. However, txt2 is the active control (when multiple controls are selected, the active control has black-filled sizing handles rather than white). When you add a control to a group of selected controls, the newly selected control is always made the active control. Finally, with the Shift key still pressed, click txt1 to add it to the group of selected controls. All the controls should now be selected and txt1 should be the active control.

graphics/bookpencil.gif

Clicking a selected control while Shift is held down deselects the control.

You can combine the two selection techniques when needed. For instance, you could first lasso all controls to select them. If the active control isn't the one you want it to be, you could hold the Shift key down and click the control you want made active, thereby deselecting it. Clicking the control a second time while still holding down the Shift key would again select the control. Because the control would then be the last control added to the selected group, it would be made active.

graphics/bookpencil.gif

If you must click the same control twice, such as to deselect and then reselect, do so slowly. If you click too fast, C# interprets your actions as a double-click, and it creates a new event handler for the control.

Aligning Controls

Now that you've selected all three controls, open C#'s Format menu (see Figure 6.5). The Format menu has a number of submenus containing functions to align, size, and format groups of controls. Open the Align submenu now to see the available options (see Figure 6.6).

Figure 6.5. Use the Format menu to quickly whip an interface into shape.

graphics/06fig05.jpg


Figure 6.6. The Align menu makes it easy to align an edge of a group of controls.

graphics/06fig06.jpg


The top three items on the Align menu are used to align the selected controls horizontally, and the middle three items align the selected controls vertically. The last item, To Grid, will snap the corners of all the selected controls to the nearest grid points. Choose Align Lefts now, and C# aligns the left edges of the selected controls. Notice how the Left edge of the active control is used as the baseline for the alignment (see Figure 6.7).

Figure 6.7. The property values of the active control are always used as the baseline values.

graphics/06fig07.jpg


Making Controls the Same Size

In addition to aligning controls, you can als o make all selected controls the same sizeHeight, Width, or Both. To do this, use the Make Same Size submenu on the Format menu (see Figure 6.8). Make all your controls the same size now by choosing Both from the Make Same Size menu. As with the Align function, the values of the active control are used as the baseline values.

Figure 6.8. Use this menu to quickly make a group of controls the same size.

graphics/06fig08.jpg


Evenly Spacing a Group of Controls

As many a salesman has said, "and that's not all!" You can also make the spacing between controls uniform using the Format menu. Try this now: open the Vertical Spacing submenu of the Format menu and then choose Make Equal. All the controls are now evenly spaced . Next, choose Decrease from the Vertical Spacing menu and notice how the spacing between the controls decreases slightly. You can also increase the vertical spacing or completely remove vertical space from between controls using this menu. To perform the same functions on the horizontal spacing between controls, use the Horizontal Spacing submenu of the Format menu. Save your project now by clicking the Save All button on the toolbar.

Setting Property Values for a Group of Controls

You can change a property value in the Properties window when multiple controls are selected, and the change will be made to all controls. To do this, make sure all three controls are still selected and then display the Properties window.

When a group of controls is selected, the Properties window appears with some modifications (see Figure 6.9):

  • No Name property is shown. This occurs because it's not allowable to have two controls with the same name, so C# won't even let you try.

  • Only properties shared by all controls are displayed. If you had selected a label control and a text box, for example, only the properties shared by both control types would appear.

  • For properties in which the values of the selected controls differ (such as the Location property in this example), the value is left empty in the Properties window.

Figure 6.9. You can view the property values of many controls at once, with some caveats.

graphics/06fig09.jpg


Entering a value in any property changes the corresponding property for all selected controls. To see how this works, change the BackColor property to a shade of yellow, and you'll see that all controls have their BackColor set to yellow.

Anchoring and Autosizing Controls

One of my favorite additions to the forms engine in C# is the capability to anchor controls to one or more edges of a form so that controls can now size themselves appropriately when the user sizes the form. In the past, you had to use a (usually cumbersome) third-party component or resort to writing code in the form Resize event to get this behavior, but it's an intrinsic capability of C#'s form engine.

The default behavior is that controls are docked to the top and left edges. What if you want a control to always appear in the lower-left corner of a form? This is precisely what the Anchor property is designed to handle.

The easiest way to understand how anchoring works is to do it.

  1. Create a new Windows Application called Anchoring Example.

  2. Change the name of the default form to fclsAnchoringExample and set the form's Text property to Anchoring Example.

  3. Change the main entry point to reflect the new form name.

  4. Add a new button to the form and name it btnAnchor.

  5. Run the project by pressing F5.

  6. Click and drag the border of the form to change its size.

Notice that no matter what size you change the form to, the button stays in the upper-left corner of the form (see Figure 6.10).

Figure 6.10. By default, controls are anchored to the upper-left corner of the form.

graphics/06fig10.jpg


Stop the running project now by choosing Stop Debugging from the Debug menu. Click the button on the form to select it, click the Anchor property, and then click the drop-down arrow that is displayed. You'll see a drop-down box that is unique to the Anchor property (see Figure 6.11).

Figure 6.11. You use this unique drop-down box to set the Anchor property of a control.

graphics/06fig11.jpg


The gray square in the center of the drop-down box represents the control whose property you are setting. The thin rectangles on the top, bottom, left, and right represent the possible edges to which you can dock the control; if a rectangle is filled in, the edge of the control facing that rectangle is docked to that edge of the form.

  1. Click the rectangle above the control so that it's no longer filled in, and then click the rectangle to the right of the control so that it is filled in.

  2. Click any other property to close the drop-down box. The Anchor property should now read LeftRight.

  3. Press F5 to run the project, and then drag an edge of the form to make it larger.

Pretty odd, huh? What C# has done is anchored the left edge of the button to the left edge of the form and anchored the right edge of the button to the right edge of the form (see Figure 6.12). Really, anchoring means keeping an edge of the control a constant relative distance from an edge of the form, and it's an unbelievably powerful tool for building interfaces. Now you can make forms that users can resize, but you write little or no code to make the interface adjust accordingly . One caveat: depending on their anchor settings, controls may disappear if the form is shrunk quite small.

Figure 6.12. Anchoring is a powerful feature for creating adaptable forms.

graphics/06fig12.jpg


Creating a Tab Order

Tab order is something that is often (emphasis on often ) overlooked. You're probably familiar with tab order as a user, although you may not realize it. When you press Tab while on a form, the focus moves from the current control to the next control in the tab order. This allows easy keyboard navigation on forms. The tab order for controls on a form is determined by the TabIndex properties of the controls. The control with the TabIndex value of 0 is the first control that receives the focus when the form is shown. When you press Tab, the control with the TabIndex of 1 receives the focus. When you add a control to a form, C# assigns the next available TabIndex value. Each control has a unique TabIndex value, and TabIndex values are always used in ascending order.

If the tab order isn't set correctly for a form, pressing Tab will cause the focus to jump from control to control in no apparent order. This really isn't a way to impress users.

The forms engine in C# has a far superior way to set the tab order for controls on a form. Create a new Windows Application named Tab Order, change the name of the default form to fclsTabOrder, set the Text property of the form to Tab Order Example and update the entry point with the fclsTabOrder reference.

Add three text box controls to the form and set their properties as follows:

Property Value Property Value Property Value
Name TextBox1 Name TextBox2 Name TextBox37
Location 90,120 Location 90,50 Location 90,190

Save the project by clicking the Save All button on the toolbar and then press F5 to run the project. Notice how the middle text box is the one with the focus. This is because it's the first one you added to the form and therefore has a TabIndex value of 0. Press Tab to move to the next control in the tab order (the top control); then press Tab once more and the focus jumps to the bottom control. Obviously, this isn't productive. Stop the project now by choosing Stop Debugging from the Debug menu (or simply close the form).

You're now going to set the tab order via the new visual method. Choose Tab Order from the View menu; notice how C# superimposes a set of numbers over the controls (see Figure 6.13). The number on a control indicates its TabIndex property value. Now it's very easy to see that the tab order is incorrect. Click the top control. Notice how the number over the control changes to 0. Click the middle control and you'll see its number change to 1. As you click controls, C# assigns the next highest number to the clicked control. Choose Tab Order from the View menu again to take the form out of Tab Order mode. Run the project again and you'll see that the top control is the first to get the focus, and pressing Tab now moves the focus logically.

Figure 6.13. The numbers over each control indicate the control's TabIndex.

graphics/06fig13.jpg


graphics/bookpencil.gif

To programmatically move the focus via the tab order, use the SelectNextControl() method of a control or a form.

To remove a control from the tab sequence, set its TabStop property to false. When a control's TabStop property is set to false, users can still select the control with the mouse, but they can't enter the control using the Tab key. You should still set the TabIndex property to a logical value so that if the control receives the focus (such as by being clicked), pressing Tab will move the focus to the next logical control.

Layering Controls (Z-Order)

Tab order and visual alignment are key elements for effectively placing controls on forms. However, these two elements address control placement in only two dimensionsthe x,y axis. At times, you may need to have controls overlap, although it's rare that you'll need to do so. Whenever two controls overlap, whichever control is added to the form most recently appears on top of the other (see Figure 6.14). You can control the ordering of controls using the Order submenu of the Format menu (see Figure 6.15).

Figure 6.14. Controls can overlap.

graphics/06fig14.jpg


Figure 6.15. The Order menu is used to adjust the layering order of overlapping controls.

graphics/06fig15.jpg


To send a control backward in the layering order, click it once to select it and then choose Send to Back from the Order menu. To bring the control forward in the layering order, select the control and choose Bring to Front from the Order menu.

graphics/bulb.gif

You can accomplish the same thing in C# code by invoking the BringToFront or SendToBack methods of a control.


   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

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