Читать книгу C# 24-Hour Trainer - Stephens Rod - Страница 24
Section I
The Visual Studio IDE and Controls
Lesson 2
Creating Controls
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.
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.
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.
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 msdn.microsoft.com/library/ms229002.aspx.
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, and numberOfEmployeesCoveredByInsurancePlanTrackBar 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.
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 Left property of the label named greetingLabel to 100. That moves the label so it's 100 pixels from the left edge of its container:
The following code shows a complete event handler:
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:
NOTE
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:
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: