24
LESSON 2 Creating Controls
WHAT’S IN A NAME, PART 3
Most C# developers add a controls type as a suffix to its name as in
firstNameTextBox or resultLabel, but it’s becoming more common for devel-
opers 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 wont need to
change the code that refers to the control.
For example, suppose your program uses a
TrackBar to let the user specify the
number of UFO detectors to purchase. If you name this control
numUfoDetectors-
Value
, they 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 sufx completely as in
numUfoDetectors, although
that can be confusing if you need more than one control to represent a similar con-
cept or 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 and you can see a summary of key properties
for specific controls in Appendix B, but for now Table 2-1 summarizes some of the most useful proper-
ties. Note that not all controls have every property. For example, a
Button cannot display a border so
it has no
BorderStyle property.
TABLE 21
PROPERTY PURPOSE
Anchor
Determines how the control sizes itself to use the available space. This property
is described further in Lesson 3.
AutoSize
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.
BackColor
Determines the control’s background color.
BackgroundImage
Determines the image that the control displays.
BorderStyle
Determines whether the control displays a border. This can be None,
FixedSingle, or Fixed3D.
Dock
Determines how the control sizes itself to use the available space. This prop-
erty is described further in Lesson 3.
596906c02.indd 24 4/7/10 12:31:32 PM
Setting Control Properties
25
PROPERTY PURPOSE
Enabled
Determines whether the control will interact with the user. Many controls dis-
play a special appearance when disabled such as being grayed out. This can
be
True or False.
Font
Determines the font that the control uses to display text.
ForeColor
Determines the control’s foreground color. For controls that display text, this
is usually the text’s color.
Image
Determines the image that the control displays. (Some controls have Image,
others have
BackgroundImage, a few have both, and some cannot display
any image. No one said this was completely consistent!)
Items
For controls such as ListBox and ComboBox, this is the list of items that the
user can select.
Location
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.
Name
Gives the control a name that your code can use. You should always give a
good name to any control that you will refer to in code.
Size
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.
Tag
This property can hold any value that you want. For example, you might put
text or a number in several
ButtonsTag properties so the code can easily
tell the
Buttons apart.
Text
Many controls have a Text property that determines what the control displays.
For
Labels and TextBoxes, Text determines the text they show (pretty obvi-
ous). For controls such as
ComboBoxes and ListBoxes, Text determines
the control’s current selection. For a
Form, which in some sense is really just
another kind of control,
Text determines what’s displayed in the title bar.
TextAlign
Determines how text is aligned within the control.
Visible
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. You can experiment with some of the other properties such as
Image and ForeColor if you like.
596906c02.indd 25 4/7/10 12:31:32 PM
26
LESSON 2 Creating Controls
Modifying Properties in Code
This lesson doesnt 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. Besides, its easy, sort of fun, and it’ll let you
make a program that does something more than just sitting there looking pretty.
First, to make a simple event handler, double-click the control in the Form Designer. That opens the
Code Editor and creates an empty event handler for the controls 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 controls 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 semi-
colon. For example, the following statement sets the
Left property of the label named greetingLabel
to 100. That moves the label so it is 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.
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
arent 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 assign it a string value. The following
code sets the
greetingLabel control’s Text property to the string Hello.
greetingLabel.Text = “Hello”;
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 rela-
tively simple and useful is
Color.
596906c02.indd 26 4/7/10 12:31:32 PM
Arranging Controls
27
Notice that you must include the string “Hello” in double quotes to tell Visual
C# that this is a literal string and not some sort of C# command. If you leave
the quotes off, Visual 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.
A control’s ForeColor and BackColor properties have the data type Color so you cannot simply set
them 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 its actually quite easy.
For example, the following two statements set a
Label’s ForeColor and BackColor 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 les-
son’s code download on the book’s web site, 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 follow-
ing 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 other controls. Figure 2-5 shows the Form Designer
displaying light blue snap lines indicating that the control is a standard distance (12 pixels) away
from the form’s top and left edges.
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.
596906c02.indd 27 4/7/10 12:31:33 PM
28
LESSON 2 Creating Controls
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 (6 pixels) below
the first button.
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 Labels text baseline lines
up with the baseline of the second
Button.
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 other textboxes, is a standard distance from the textboxes
above and below, is a standard distance from the forms right edge,
and has its baseline lined up with the Street label.
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 con-
trol’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.
FIGURE 25
FIGURE 26
FIGURE 27
FIGURE 28
596906c02.indd 28 4/7/10 12:31:33 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.142.2