Creating Controls - The Visual Studio IDE and Controls - C# 24-Hour Trainer (2015)

C# 24-Hour Trainer (2015)

Section I

The Visual Studio IDE and Controls

Lesson 2

Creating Controls

Way back in the computer stone ages, when programmers worked by candlelight on treadle-powered computers and hand-carved wooden monitors, input and output were very simple. The computer wrote text in toxic green on the bottom of a monitor and the text scrolled up as the monitor became full. The user typed on a keyboard to enter text at a single input prompt, and that was about it. Multiple windows performing useful work simultaneously, mice, and forms displaying many labels and textboxes, buttons, scrollbars, and full-color images existed only in the fevered dreams of science-fiction writers.

Today these things are so commonplace that we take them completely for granted. They appear in desktop software, web pages, laptops, handheld computers, and even cell phones.

Building these sorts of objects in the old days would have been extremely difficult, but today it's practically trivial to add them to your application.

You already saw in Lesson 1 how easy it is to make an application (albeit a trivial one) that displays a form that runs independently of the others on the computer. It's almost as easy to use labels, textboxes, buttons, scrollbars, images, menus, popups, and everything else that makes up a modern application.

C# makes all of these objects and more available as controls.

In this lesson, you learn how to add controls to a form. You learn how to size, position, and arrange controls. You also learn how to use a control's properties to change its appearance and behavior at design time and at run time. When you're done with this lesson, you'll be able to build a professional-looking form.

Understanding Controls

A control is a programming entity that combines a visible appearance on the screen and code to manage it. The code defines the control's appearance and behavior.

For example, a TextBox control displays a blank area on the screen where the user can type information. The code inside the control determines how the control draws itself and provides normal textbox features such as multiline or single-line behavior; scrolling and scrollbars displayed as needed; copy, cut, and paste; a context menu displayed when you right-click the control; the ability to navigate when the user presses the Tab key; and much more.

What's in a Name?

By convention, in C# the names of control types (and other types) use Pascal casing where multiple words are strung together with the first letter of each word capitalized; for example, TextBox, ProgressBar, Button, and PictureBox.

In addition to controls, C# provides components. A component is similar to a control except it has no visible piece on the form. For example, the Timer component acts as a clock to let the program do something at regular intervals. The Timer interacts with the program but doesn't display anything visible to the user. (Some components such as ErrorProvider and ToolTip may display visible effects on the screen, but the components themselves are not visible on the form.)

The features of controls (and components) fall into three categories: properties, methods, and events.


A property determines the appearance and state of a control. If a Car were a control, its properties would be things like Color, TransmissionType, CurrentSpeed, and NumberOfCupHolders. Your program could set a Car's Color to HotPink (to attract the attention of other drivers) or set its CurrentSpeed to 110 (to attract the attention of the police).

For a programming example, the TextBox control has a Font property that determines the font it uses and a ForeColor property that determines the color of its text.


A method is a feature of a control that makes the control perform some action. Your code can call a method to make the control do something. For example, the Car control might have methods such as Start, Stop, EjectPassenger, and OilSlick. Your program could call the OilSlick method to make the car spray oil out the back so you can escape from spies.

For a programming example, the TextBox has a Clear method that blanks the control's text and an AppendText method that adds text to the end of whatever the control is currently displaying.


An event occurs when something interesting happens to the control. The control raises or fires the event to tell the program that something happened. For example, a Car might have RanOutOfGas and Crashed events. The Car control would raise the Crashed event to tell the program that the user had driven it into a tree. The program could then take action such as calling an ambulance and a tree surgeon.

For a programming example, the TextBox has a TextChanged event that tells the program that its text has changed. When the event occurs, the program could examine the text to see if the user had entered a valid input. For example, if the TextBox should hold a number and the user entered “One,” the program could beep and change the TextBox's BackColor property to Yellow to indicate an error.

Later lessons discuss events and the code that handles them in greater detail. This lesson focuses on adding controls to a form, arranging them, and setting their properties.

Creating Controls

Adding controls to a form is easy. In fact, it's so easy and there are so many different ways to add controls to a form that it takes a while to describe them all.

Start by creating a new project as described in Lesson 1. Open the form in the Form Designer. (If the form isn't already open, double-click it in Solution Explorer.)

The following list describes some of the ways you can put controls on the form:

· Click a tool in the Toolbox to select it. Then click and drag on the form. When you release the mouse, Visual Studio creates the control in the area you selected and then selects the pointer in the Toolbox.

· Click a tool in the Toolbox to select it. Then hold down the Ctrl key while you click and drag on the form to place a copy of the control on the form. When you release the mouse, Visual Studio creates the control in the area you selected and keeps the control's tool selected in the Toolbox so you can make another control of that type.

· Double-click a tool in the Toolbox to create an instance of the control on the form at a default size and position. (You'll then probably want to resize and reposition it.)

· Select one or more controls that are already on the form, press Ctrl+C to copy them, and then press Ctrl+V to paste them onto the form. You can even copy and paste from one instance of Visual Studio to another.

· Select one or more controls on the form. While holding down the Ctrl key, drag the controls to a new location. Visual Studio makes a copy of the controls, leaving the originals where they started.


You have several ways to select controls on the Form Designer. Click a control to select only it. Click and drag to select multiple controls.

Hold down the Shift or Ctrl key while clicking or clicking and dragging to toggle whether controls are in the current selection.

And, if you want to deselect all controls, simply click an empty part of the form or press Esc.

The first method (select a tool and then click and drag to create a control) is probably used most often, but some of the other methods are particularly useful for creating groups of similar controls.

For example, the form in Figure 2.1 displays five rows, each of which holds a Label and a TextBox. You could easily build all of these controls individually, but you can build them even faster by using copy and paste. First place one Label and TextBox on the form, arrange them next to each other, and give them any property values that you want all of the Labels or TextBoxes to share. (For example, you may want to set their fonts or colors.) Now click and drag to select both controls, copy and paste, and drag the new controls into position. Repeat this three more times and you'll have all of the controls in position. You'll still need to change the Labels' text but the basic arrangement will be done without going back and forth to the Toolbox.

Image described by surrounding text.

Figure 2.1

Setting Control Properties

After you've added controls to a form, you can use the Properties window to view and change their property values. If you have more than one control selected, the Properties window shows only the properties that the controls have in common.

For example, if you select a TextBox and a Label, the Properties window shows the Text property because both Labels and TextBoxes have a Text property. However, it won't display the Multiline property because the TextBox control has that property but the Label control does not.

The Properties window provides special support for many control properties. For example, Figure 2.2 shows the Properties window when a TextBox is selected.

Screenshot of the Properties window presenting the highlighted Font property displaying sub-properties (Name, Size, Unit, Bold, and others). A description of Font is displayed below.

Figure 2.2

Notice that the Font property contains its own sub-properties: Name, Size, Unit, Bold, and so forth. Click the plus or minus sign next to a property to expand or collapse it and show or hide its sub-properties.

Also notice in Figure 2.2 the ellipsis to the right of the Font property. If you click that ellipsis, the dialog shown in Figure 2.3 appears. You can use this dialog to edit the font sub-properties and see a sample of the font.

Font dialog box presenting three sub-properties—Font, Font style, and Size—with two checkbox options for Effects, a sample preview, and the Script set to Western. OK and Cancel buttons are at the upper right side.

Figure 2.3

The Properties window provides appropriate support when it can for other properties. Many properties can hold only certain values. For example, the Font's Italic, Bold, Strikeout, and Underline sub-properties can only take the values True or False. The Font's Unit sub-property can only take the values World, Pixel, Point, Inch, Document, and Millimeter. In these cases, the Properties window provides a dropdown listing the allowed choices.

Figure 2.4 shows the editor that the Properties window displays when you click the dropdown arrow to the right of a TextBox's BackColor property. The Custom tab lets you pick a color from a palette, the Web tab lets you pick standard web page colors, and the System tab lets you pick system colors such as the normal control background color or the menu highlight color.

Image described by surrounding text.

Figure 2.4

By using the Properties window's editors and typing in values when there is no editor, you can change a control's appearance and behavior.

Control Names

Whenever you create a control, Visual Studio gives it a rather nondescript name such as label2, textBox5, or pictureBox1. Although these names tell you what kind of object the control is, they don't tell you what it is for and that's much more important when you later need to use the control in your code. Names like firstNameTextBox, hatSizeTrackBar, and mediaTypeComboBox are much more meaningful than textBox3 and textBox7.

Note that you don't need to give good names to every control, just the ones that you will need to use later in the code. You often don't need to name Labels, GroupBoxes, and other purely decorative controls.

You can learn more about Microsoft's naming conventions on the web page “Guidelines for Names” at

What's in a Name, Redux

Earlier in this lesson I said that control type names use Pascal casing. By convention, the names of specific instances of controls use camel casing, where multiple words are strung together with the first letter of each word capitalized, except for the first word. For example, the control type TextBox uses Pascal casing and the specific control name firstNameTextBox uses camel casing.

It's called camel casing because it sort of looks like a camel lying down: low at the ends with one or more humps in the middle. I guess stateLabel would be a dromedary (one-humped) camel, priceTextBox would be a Bactrian (two-humped) camel, andnumberOfEmployeesCoveredByInsurancePlanTrackBar would be some sort of camel created by Dr. Seuss.

What's in a Name, Part 3

Most C# developers add a control's type as a suffix to its name as in firstNameTextBox or resultLabel, but it's becoming more common for developers to use a more generic word such as value or field. The idea is that if you decide to change the type of control that handles the value, you won't need to change the code that refers to the control.

For example, suppose your program uses a TrackBar to let the user select the number of UFO detectors to purchase. If you name this control numUfoDetectorsValue, then you won't need to change the code if you later decide to let the user select the value from a NumericUpDown control instead of a TrackBar.

Some developers even omit the suffix completely as in numUfoDetectors, although that can be confusing if you need more than one control to represent a similar concept or if you want a variable inside the code that holds the numeric value represented by the control.

For now, I recommend that you stick with the control's full type name as a suffix.

Popular Properties

You'll learn about key control properties as you go along, but for now Table 2.1 summarizes some of the most useful properties. Note that not all controls have every property. For example, a Button cannot display a border (or it always displays a border, depending on your point of view) so it has no BorderStyle property.

Table 2.1




Determines how the control sizes itself to use the available space. This property is described further in Lesson 3.


Determines whether the control automatically resizes itself to fit its contents. This can be True or False. By default, Labels are born with AutoSize = True.


Determines the control's background color.


Determines the image that the control displays.


Determines whether the control displays a border. This can be None, FixedSingle, or Fixed3D.


Determines how the control sizes itself to use the available space. This property is described further in Lesson 3.


Determines whether the control will interact with the user. Many controls display a special appearance when disabled such as being grayed out. This can be True or False.


Determines the font that the control uses to display text.


Determines the control's foreground color. For controls that display text, this is usually the text's color.


Determines the image that the control displays. (Some controls have Image, others have BackgroundImage, a few have both, and many cannot display any image. No one said this was completely consistent!)


For controls such as ListBox and ComboBox, this is the list of items that the user can select.


Gives the control's location in pixels from the upper-left corner of whatever it is in (for now, assume it's in the form). Location includes X and Y sub-properties. For example, the value (10, 20) means the control is 10 pixels from the form's left edge and 20 pixels from its top edge.


Gives the control a name that your code can use to refer to it later. You should always give a good name to any control that you will refer to in code.


Gives the control's width and height in pixels. For example, the value (75, 30) means the control is 75 pixels wide and 30 pixels tall.


This property can hold any value that you want to store with the control. For example, you might put text or a number in the Tag properties of some Buttons so the code can easily tell the Buttons apart.


Many controls have a Text property that determines what the control displays. For Labels and TextBoxes, Text determines the text they show (pretty obvious). For controls such as ComboBoxes and ListBoxes, Text determines the control's current selection. For a Form, which in a real sense is just another kind of control, Text determines what's displayed in the title bar.


Determines how text is aligned within the control.


Determines whether the control is visible. This can be True or False. Set it to False to hide a control from the user.

If you want some practice with these properties, create a new project and give them a try. Create a Button and set its Text property. Also click the form and set its Text property. Change the form's Font property and see what happens to the form and the button it contains. Experiment with some of the other properties such as Image and ForeColor if you like.

Modifying Properties in Code

This lesson doesn't really go into handling control events very much (that's the subject of Lesson 4), but I do want to explain how to set properties in code and you need event handlers to do that. Besides, it's easy and sort of fun, and it'll let you make a program that does something more than just sitting there looking pretty.

To make a simple event handler for a control, double-click the control in the Form Designer. That opens the Code Editor and creates an empty event handler for the control's default event. For Button controls, that's the Click event. Whenever the user clicks the control at run time, it raises its Click event and this code executes.

To change a property in code, type the control's name, a dot (or period), the name of the property, an equals sign, and finally the value that you want to give the property. Finish the line of code with a semicolon. For example, the following statement sets the Leftproperty of the label named greetingLabel to 100. That moves the label so it's 100 pixels from the left edge of its container:

greetingLabel.Left = 100;

The following code shows a complete event handler:

// Move the Label.

private void moveLabelButton_Click(object sender, EventArgs e)


greetingLabel.Left = 100;


In this code, I typed the first line that starts with two slashes. That line is a comment, a piece of text that is contained in the code but that is not executed by the program. Any text that comes after the // characters is ignored until the end of the current line. You can (and should) use comments to make your code easier to understand. They don't make the executable program bigger or slower, so don't be stingy with your comments!

I also typed the line that sets the Label's Left property.

Visual Studio typed the rest when I double-clicked the moveLabelButton control. You don't need to worry about the details of this code right now, but briefly the sender parameter is the object that raised the event (the Button in this example) and the e parameter gives extra information about the event. The extra information can be useful for some events (for example, in the MouseClick event it tells where the mouse was clicked), but it's not very interesting for a Button's Click event.

Simple numeric values such as the 100 used in this example are easy to set in code, but some properties aren't numbers. In that case, you must set them to values that have the proper data type.

For example, a Label's Text property is a string so you must give it a string value. The following code sets the greetingLabel control's Text property to the string Hello:

greetingLabel.Text = "Hello";


Notice that you must include the string Hello in double quotes to tell C# that this is a literal string and not some sort of C# command. If you leave the quotes off, C# gets confused and gives you the error “The name ‘Hello’ does not exist in the current context.”

Over time, you'll get used to messages like this and they'll make sense. In this case, the message just means, “I don't know what the word ‘Hello’ means.”

Other property values have more exotic data types such as Date, AnchorStyles, Point, and BindingContext. When you set these properties, you must make sure that the values you give them have the correct data types. I'm going to ignore most of these for now, but one data type that is relatively simple and useful is Color.

A control's ForeColor and BackColor properties have the data type Color so you cannot simply set them equal to strings such as Red or Blue. Instead you must set them equal to something that also has the type Color. The easiest way to do that is to use the colors predefined by the Color class. This may seem a bit confusing, but in practice it's actually quite easy.

For example, the following two statements set a Label's BackColor and ForeColor properties to HotPink and Blue, respectively:

greetingLabel.BackColor = Color.HotPink;

greetingLabel.ForeColor = Color.Blue;

The following code shows how the MoveButton example program, which is available as part of this lesson's code download on the book's website, changes several Label properties when you click a Button:

// Change a Label's properties.

private void moveLabelButton_Click(object sender, EventArgs e)


greetingLabel.Left = 100;

greetingLabel.Text = "Hello";

greetingLabel.BackColor = Color.HotPink;

greetingLabel.ForeColor = Color.Blue;


Arranging Controls

The Form Designer provides several tools to help you arrange controls at design time. The following sections describe some of the most useful: snap lines, arrow keys, the Format menu, and the Layout toolbar.

Snap Lines

When you drag a control around on the form, the Form Designer displays snap lines that show how the control lines up with the form and with other controls. Figure 2.5 shows the Form Designer displaying light blue snap lines indicating that the control is standard distances away from the form's top and left edges.

Image described by surrounding text.

Figure 2.5

You can drag the control away from this position and, if you do so, the snap lines disappear. When you drag the control close to one of the form's edges, the control jumps to the standard distance and the Form Designer displays the snap lines again.

The Form Designer also displays snap lines to show how controls align. In Figure 2.6, I dragged a second Button below the first. Different snap lines show that:

· The second Button is the standard distance from the form's left edge.

· The second Button's left and right edges line up with the first Button's edges.

· The second Button is a standard distance below the first Button.

Image described by surrounding text.

Figure 2.6

Other snap lines show how the control contents line up. In Figure 2.7 snap lines show that the Label is the standard distance from the second Button and that the Label's text baseline lines up with the baseline of the second Button.

Image described by surrounding text.

Figure 2.7

For a more realistic example, consider Figure 2.8. In this figure I was laying out a small data entry form, and I wanted all of the Labels and TextBoxes to line up nicely. In this figure, snap lines show that the Street TextBox is lined up on the left and right with the otherTextBoxes, is a standard distance from the TextBoxes above and below, is a standard distance from the form's right edge, and has its baseline lined up with the Street Label.

Image described by surrounding text.

Figure 2.8

Arrow Keys

In addition to dragging controls with the mouse, you can move controls by pressing the arrow keys. Select one or more controls and then use the left, right, up, and down arrow keys to move the control(s) one pixel at a time. This method is slower than using the mouse but gives you finer control.

When you move controls with the arrow keys, the Form Designer doesn't display snap lines so you may want to keep an eye on the control's Location property in the Properties window to see where it is.

The Format Menu and Layout Toolbar

The Format menu contains many commands that arrange one or more controls. Table 2.2 summarizes the Format menu's submenus.

Table 2.2




Aligns groups of controls on their lefts, middles, rights, tops, bottoms, or centers.

Make Same Size

Makes controls have the same width, height, or both.

Horizontal Spacing

Adjusts the horizontal spacing between controls. It can make the space between controls equal, smaller, larger, or zero.

Vertical Spacing

Works like the Horizontal Spacing submenu except it adjusts the vertical spacing between controls.

Center in Form

Centers the controls vertically or horizontally in their container. If the controls are inside a container like a Panel or GroupBox, these commands center the controls within the container, not the form.


These commands send a control to the front or back of the stacking order. This is useful if you have controls that overlap so some are behind others.

The Layout toolbar contains the same commands as the Format menu but in a handy toolbar so they're easier to use. The buttons display little pictures that show how they align controls.


How these tools arrange controls depends on how you select the controls. One of the selected controls, normally the first one you select, is the group's dominant control. The dominant control is marked with white boxes at its corners, whereas the other controls are marked with black boxes.

When you use an arranging tool, the dominant control determines how the others are arranged. For example, if you select the Format 1 Align 1 Lefts command, the other controls are moved so their left edges line up with the dominant control's left edge.

To change the dominant control in a selected group, click the one you want to be dominant (without holding down the Ctrl or Shift keys).

WPF Controls

WPF applications use their own set of controls, some of which are similar to controls used by Windows Forms applications. Visual Studio for Windows lets you create WPF applications in roughly the same way Visual Studio for Windows Desktop lets you make Windows Forms applications. Both provide an editor where you can click and drag to create controls and a Properties window where you can set control properties.

One big difference is that Visual Studio also displays a XAML code editor for WPF applications. XAML, which stands for “eXtensible Application Markup Language” and which is usually pronounced “zammel,” is a language that Visual Studio uses to define user interfaces for WPF applications.

Sometimes it's easier to edit the XAML code directly than it is to use the Window editor. In particular, it's often easier to make copies of controls by copying and pasting XAML code (and changing the new controls' names) than it is to copy controls in the Window editor.

For now, you should probably start with the Window editor, but you may also want to look at the XAML code and experiment with it a bit to see how it works.

Try It

In this Try It, you get some practice building a user interface. You place controls on a form and arrange them so they line up nicely. You also get some practice setting control properties at design time and changing them at run time.

Lesson Requirements

In this lesson, you:

· Add controls to a form and arrange them as shown in Figure 2.9. (Note the form's title and the fact that the form has a non-resizable border.)Screenshot of the New Customer window presenting a small data entry form with six labels and six textboxes. OK button is set as the form's default button with the result label “New Customer Created” at the bottom.

Figure 2.9

· Give the key controls names.

· Set properties at design time on the result label (at the ­bottom in Figure 2.9) to make the label:

· Display its text centered.

· Show a border.

· Use a 16-point font.

· Remain invisible until the user clicks one of the buttons.

· Make the OK button be the form's default button so it fires when the user presses Enter. Make the Cancel button be the form's cancel button so it fires when the user presses Esc.

· Add code behind the OK button to display the result label with a green background as shown in Figure 2.9.

· Add code behind the Cancel button to display the result label with a hot pink background and the text “Operation Canceled.”


You can download the code and resources for this lesson from the website at


· Create the First Name Label and TextBox first and arrange them. Then copy and paste them to make more Labels and TextBoxes.

· Use the Format menu or Layout toolbar to center the buttons and the result label.


· Add controls to a form and arrange them as shown in Figure 2.9. (Note the form's title and the fact that the form has a nonresizable border.)

1. Start a new project named NewCustomer. Remember to put it somewhere easy to find.

2. Use the Properties window to set the form's Text property to New Customer.

3. Use the Properties window to set the form's FormBorderStyle property to FixedDialog. (Feel free to experiment with the other values.)

4. Create the First Name TextBox.

a. Click the Toolbox's TextBox tool and then click and drag to place a TextBox on the form.

b. Drag the TextBox into the form's upper-right corner until the snap lines show that it is a standard distance from the top and right edges of the form.

5. Create the First Name Label.

a. Click the Toolbox's Label tool and then click and drag to create the Label.

b. Drag the Label to the form's upper-left corner so the snap lines show that the Label is a standard distance from the form's left edge and that its baseline aligns with the TextBox's baseline.

c. To determine the Label's width, you need to set its text. Use the Properties window to set the Label's Text property to First Name.

d. Click the TextBox. Click the drag handle on the TextBox's left edge and drag it until it is a standard distance from the Label.

6. Make copies of the Label and TextBox.

a. Click and drag to select both the Label and the TextBox.

b. Press Ctrl+C to copy the controls. Then press Ctrl+V to paste new copies of the controls.

c. With the new controls still selected, click and drag the TextBox until the snap lines show it is standard distances away from the TextBox above and from the form's right edge.

d. Use the Properties window to set the new Label's Text property to Last Name.

e. Repeat this four more times (using appropriate Text values) until you have five rows of Labels and TextBoxes.

7. Make the ZIP Label.

a. Set the bottom TextBox's Text property to 12345-6789. Then use the TextBox's left drag handle to resize it so it's a bit bigger than its Text value (see Figure 2.9).

b. Create a Label for the ZIP code and set its Text property to ZIP. Drag it so the snap lines show its baseline aligns with the baseline for the Label and TextBox on that same line, and it is the standard distance to the left of the TextBox.

c. Use the Properties window to set the TextBox's TextAlign property to Right.

8. Make the State ComboBox.

a. Use the Toolbox to make a ComboBox. Set its Text property to WW and resize it so the text fits reasonably well.

b. Drag the ComboBox so the snap lines show its baseline aligns with the Labels on that row and its left edge aligns with the left edges of the TextBoxes above.

c. With the ComboBox selected, look in the Properties window and click the Items property. Then click the ellipsis (…) button on the right to open the String Collection Editor. Enter CO, AZ, WY, UT, and any other state abbreviations that you want to use and click OK. (If you want to enter Confusion and Denial, you'll need to make the ComboBox wider.)

d. Use the Properties window to set the DropDownStyle property to DropDownList.


The DropDownStyle value Simple makes the ComboBox display a TextBox where the user can type and a list below it where the user can make selections.

The value DropDown makes the ComboBox display a TextBox where the user can type and a dropdown arrow that makes a dropdown list appear.

The value DropDownList is similar to DropDown except the user can only select from the dropdown list and cannot type new values. DropDownList is often the best choice because it prevents the user from typing invalid values.

9. Make the Buttons.

a. Double-click the Toolbox's Button tool twice to make two Buttons with standard sizes.

b. Drag one Button so it is a nice distance below the TextBoxes. Drag the other Button so it's aligned vertically with the first, positioning it some reasonable distance to the side (the exact distances don't matter here).

c. Click and drag to select both Buttons. Select Format 1 Center in Form 1 Horizontally.

d. Use the Properties window to give the Buttons the Text values OK and Cancel.

10.Use the Toolbox to make the result Label. (Don't worry too much about its size and position right now. Just drop it somewhere close to where it is shown in Figure 2.9.)

· Give the key controls names.

1. Give the key controls the names shown in Table 2.3. You don't need to give names to the other controls because the program won't need to refer to them. (Actually this example doesn't refer to the TextBoxes or ComboBox either, but a real program certainly would. A form wouldn't contain TextBoxes and ComboBoxes that it won't use.)

Table 2.3



First Name TextBox


Last Name TextBox


Street TextBox


City TextBox


State ComboBox


ZIP TextBox


OK Button


Cancel Button


Result Label


· Set properties at design time on the result label (at the bottom in Figure 2.9) to make the label:

· Display its text centered.

1. Set the Label's TextAlign property to MiddleCenter. (Use the Properties window's TextAlign editor to select the middle position.)

2. Set the Label's AutoSize property to False.

3. Set the Label's Size property to 218, 37. (Or expand the Size property and set the Width and Height sub-properties separately.)

4. Use the Format menu or Layout toolbar to center the Label on the form.

· Show a border.

0. Set the Label's BorderStyle property to Fixed3D.

· Use a 16-point font.

0. Expand the Properties window's Font entry. Set the Size sub-property to 16.

· Remain invisible until the user clicks one of the buttons.

0. Set the Label's Visible property to False.

· Make the OK button be the form's default button so it fires when the user presses Enter. Make the Cancel button be the form's cancel button so it fires when the user presses Esc.

0. Click the form and use the Properties window to set the form's AcceptButton property to okButton.

1. Similarly, set the form's CancelButton property to cancelButton.

· Add code behind the OK button to display the result label with a green background as shown in Figure 2.9.

0. Double-click the OK button to create an event handler for its Click event.

1. Type the bold text in the following code so the event handler looks like this:

2. // Create the new customer.

3. private void okButton_Click(object sender, EventArgs e)

4. {

5. resultLabel.Text = "New Customer Created";

6. resultLabel.BackColor = Color.LightGreen;

7. resultLabel.Visible = true;


· Add code behind the Cancel button to display the result label with a hot pink background and the text “Operation Canceled.”

0. Double-click the Cancel button to create an event handler for its Click event.

1. Type the bold text in the following code so the event handler looks like this:

2. // Don't create the new customer.

3. private void cancelButton_Click(object sender, EventArgs e)

4. {

5. resultLabel.Text = "Operation Canceled";

6. resultLabel.BackColor = Color.HotPink;

7. resultLabel.Visible = true;


Now run the program and experiment with it. Notice what happens when you press the Enter and Esc keys while focus is in a TextBox. See what happens if focus is on one of the Buttons.


1. [Games] Build a checkerboard similar to the one shown in Figure 2.10. (Hints: The squares are PictureBoxes with different background colors. Give the form a bluish background. Finally, use the Format menu or Layout toolbar to align the controls.)Screenshot of Checkerboard window displaying a checkerboard with a bluish background.

Figure 2.10

2. [Games, WPF] Repeat Exercise 1 with a WPF application. (Hints: Place colored Rectangles inside a WrapPanel with a width that makes the Rectangles wrap in eight columns.)

3. [Games] Make a tic-tac-toe (or naughts-and-crosses) board similar to the one shown in Figure 2.11. (Hints: Make three Labels for each square, named after the rows and columns. For the upper-left square, name them x00Label for the little X Label, o00Label for the little O Label, and taken00Label for the big Label. Give the smaller Labels Click event handlers that set the Text property of the corresponding big Label. Don't worry about the rules such as not allowing someone to take a square that is already taken.)Image described by surrounding text.

Figure 2.11

4. [Games, WPF] Repeat Exercise 3 with a WPF application. (Hints: For each square, use a Border with Margin values set to 5. A Border can hold only one content control, so put a Canvas in each Border. Then put the three Labels inside the Canvas. Put the nine Borders inside a WrapPanel sized so they form three columns. See the video Making Event Handlers for instructions on how to make the small Labels act like buttons. Add interesting backgrounds if you like.)

5. [Games] Modify the tic-tac-toe program from Exercise 3 so instead of displaying X or O in each square, it displays pictures. Use your favorite football team logos, a cat and a dog, your picture and your boss's, or whatever. (Hints: Use PictureBoxes instead of the large Labels. Add two hidden PictureBoxes to the form. To set their Image properties, click the ellipsis next to the Image property in the Properties window, click the Import button, and browse for the image files. Finally, instead of setting a Label's Text property, theClick event handlers should set the appropriate PictureBox's Image property equal to one of the hidden PictureBox's Image properties. Set all SizeMode properties of the PictureBoxes to Zoom.)

6. [WPF] Repeat Exercise 5 with a WPF application. (Hints: Use Image controls instead of the large Labels. Use two Images with Visiblity = Hidden to store the X and O images. In an event handler, use code similar to taken21Image.Source = oImage.Source.)

7. Make a program with a Label that says “Move Me” and four Buttons with text (0, 0), (200, 200), (200, 0), and (0, 200). Make each Button move the Label to the corresponding position by setting its Left and Top properties.

8. [WPF] Repeat Exercise 7 with a WPF application. (Hints: Set the Label's position with code similar to moveMeLabel.Margin = new Thickness(0, 200, 0, 0).)

9. The solution to Exercise 7 moves its Label in two steps by setting its Left and Top properties. Modify the program so it sets the Label's Location property in a single step using code similar to this:

moveMeLabel.Location = new Point(0, 0);

10.Build a hotel menu form similar to the one shown in Figure 2.12. (Hints: Copy and paste the Labels and TextBoxes from the Try It program. To set the PictureBox's image, look in the Properties window and click the ellipsis next to the Image property. In the Select Resource dialog, click Import and browse to select a picture. Finally, set the PictureBox's SizeMode property to AutoSize.)Screenshot of the Menu window presenting three rows, each having a label and a textbox, with a picture box image at the upper right. Breakfast, Lunch, and Dinner has three checkboxes each displayed in column.

Figure 2.12

11.[WPF] Repeat Exercise 10 with a WPF application.

12.Build a form similar to the one shown in Figure 2.13. (Don't worry about making the program perform any calculations. You'll learn how to do that later.)Bill of Sale window presenting SKU#, Description, Quantity, Price Each, and Item Total headings with 4 textboxes each arranged in column. Labels and textboxes of Subtotal, 10 % Tax, and Total are displayed below.

Figure 2.13

13.[WPF] Repeat Exercise 12 with a WPF application.

14.Build a form similar to the one shown in Figure 2.14. (Search the Internet for “labeled diagram” and pick an interesting image. Use MS Paint or some other image editing program to remove the labels. Then add TextBoxes where the labels were so the user can fill them in.)Screenshot of Budgie Parts window presenting an image of a bird (budgie) with labeled parts.

Figure 2.14

15.[WPF] Repeat Exercise 14 with a WPF application.

16.Build a bar chart similar to the one shown in Figure 2.15. (Hints: Use a PictureBox for the chart's background and Labels for the bars.)Screenshot of People in Car window presenting a bar chart with five decreasing bars labeled 1–5 in the x-axis. The y-axis has increments of 5.

Figure 2.15

17.[WPF] Repeat Exercise 16 with a WPF application. Give the chart background a color gradient and label the Y axis with a sideways label that says “Occurrences.”

18.Build a bar chart similar to the one shown in Figure 2.16. (Hints: Use PictureBoxes for the bars.)Similar to Figure 2.15 but each bar contains a picture of a car.

Figure 2.16

19.[WPF hard] Repeat Exercise 18 with a WPF application but fill the bar Image controls with a tile brush that uses a small picture of a car. Set the brush's TileMode = Tile and Stretch = None. Use the XAML editor to add the code Viewport="0,0,55,27" ViewportUnits="Absolute" inside the brush's definition. The result should be bars that are tiled with little pictures of cars.

20.Modify the program you made for Exercise 18 to add tooltips for the bars. (Add a ToolTip control named peopleToolTip to the form. Then use the Properties window to set the “ToolTip on peopleToolTip” property for the bar labels. For example, make the second bar's tooltip say “2 people.”)

21.[WPF] Repeat Exercise 20 with a WPF application. (Hint: In WPF you don't need to use a ToolTip control. Just set the bars' ToolTip properties.)

22.[WPF hard] Build a WPF program similar to the one shown in Figure 2.17. (Hints: For the reflected text, use a Label. Make its Foreground brush shade from medium gray to light gray. In the Transform property category, set the scale in the Y direction to –1 and set the skew in the X direction to 30.)Screenshot of the Mirror Text window with words Mirror Text at the center with a foreground brush shade from medium to light.

Figure 2.17

23.[Games] Make a program named MovingButton. Make a Button named ­clickMeButton that says “Click Me.” Add a Timer named moveButtonTimer to the form and set its Interval property to 500.

24.Next double-click the Timer to open the code for its Tick event and add the bold text so the event handler looks like the following:

25. Random Rand = new Random();

26. private void moveButtonTimer_Tick(object sender, EventArgs e)

27. {

28. clickMeButton.Left = Rand.Next(0, 250);

29. clickMeButton.Top = Rand.Next(0, 250);


30.Now double-click the Button and add the bold text in the following code to create its event handler:

31. private void clickMeButton_Click(object sender, EventArgs e)

32. {

33. moveButtonTimer.Enabled = !moveButtonTimer.Enabled;


34.Run the program and have fun! Experiment with different values for the Timer's Interval property such as 2000 and 10.


Please select the videos for Lesson 2 online at