26
LESSON 2 Creating Controls
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. Besides, it’s 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 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 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
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 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