Professional Documents
Culture Documents
Graphical User Interfaces (GUI) allow a user to interact easily with the program using different visual
components. On the early days of the computer world, applications are text based and you type commands
and input to make the program useful. You need to memorize a long list of commands to be able to work
properly with the program. Modern software applications have graphical user interfaces. You see them in
almost every program you use now. A professional looking graphical user interface is easy in the eyes and
has a simple, yet attractive look and feel. A good graphical user interface also makes the commands more
accessible and organized by using menus and grouping components.
But creating a program with a user interface was once a tedious task. For you to even create a simple
window that displays a message, you need to type lots of codes. Creating an application with a graphical
user interface was hard until the arrival of Visual Programming. Visual Programming makes it easy for
you to create GUI applications by providing you a "canvas" where you simply drag the controls from the
toolbox. Controls are visual elements that compose the GUI. You can interact with these controls to
perform their functionality. Examples of controls are buttons, text boxes, labels, checkboxes, and radio
buttons. The term "visual" in Visual C# was from the concept of visual programming.
Microsoft uses the term Windows Forms to represent every window in an application. Visual Studio allows
you to create Windows Forms Applications easily. You can then create and design the form in the Design
View.
Figure 1 shows the Design View in Visual C# Express 2010. You can see the form and some controls
"drawn" in its surface. With the Designer View, you can see how the form will look when you run the
program. The code for drawing and initializing controls are hidden from the programmer so you can
concentrate on the functionality of the application.
You can use Visual Studio's tools for designing controls such as aligning, anchoring, docking, and resizing
controls. Visual programming saves development time and suitable for Rapid Application Development.
Other languages that do not support visual programming requires dozens of code before you can even
create a simple window that shows a short message.
Creating a
Application
Simple
Windows
Forms
You will now experience visual programming which is the "Visual" in Visual C#. Please note that this lesson
guides you to the creation of a simple windows application which uses basic event-handling. I will show
the steps for doing these and briefly discuss them. The concepts of forms, controls, event-handling, and
certain parts Visual Studio used for designing will be discussed in their respective lessons.
Open Visual C# Express and go to File > New Project. Then from the list of templates, choose Windows
Forms Application. A Windows Forms Application is a type of application that has a graphical user interface.
Name the project MyFirstWindowsApplication.
You will be presented with a blank form. The selected tab tells that you are viewing the Form1.cs file in
Designer View.
Two code files will be created that represent the form. But for now, we will concentrate on the file that is
used to add functionality to the form. The form can be viewed in two modes, the Design View and Code
View. The Designer will be shown if you are in design view. You will see here the actual form and any visual
and non-visual controls you will add soon.
You can also resize the forms by dragging the resizing handles of the form while in the Design View.
The Toolbox is divided into categories and the most commonly used controls are located in the Common
Controls category. To open a category and expose its control, simply click the category. The Toolbox will
auto-hide by default. If you don't want that behavior, then you can click the pin icon beside the close button
of the Toolbox.
To add controls to the form, choose a control in the Toolbox and double click it. Alternatively, you can drag
the control from the Toolbox to the form. Please note that you can only add controls to the client area of
the form. The client area is the blank area of the form. You can delete a control or controls by selecting it
in the designer and hitting Delete in your keyboard. Add a button control to the form. Most controls also
has resizing handles just like the form itself. Resize and position the button as shown if Figure 5.
Figure 5
Find the Text property and change its value to "Click Me".
You can also click the form in the Designer and change the Text property. When selecting the form, you
need to click on any area of the form but not on the controls it contain.
Don't mind the other parts of the code as there will be a seperate lessons that discuss them. Type the
following code inside the event handler. Please only type the code inside the event handler of the following
code. I included the event handler so you can clearly see where to type the code.
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked the button!");
}
The MessageBox class allows you to call a message box used to prompt user with messages and
information. The Show method shows the message box with a specified message. You will learn more
about the MessageBox class later. Run the program and click the button. You will be presented with a
message window with the message you specified as an argument to the Show method.
Another way of adding event handlers to events of controls especially for non-default events, is by going
to the Properties Window. To demonstrate this, let's add a Load event to the form. Go back to Design View
by clicking the Design Tab, or using the Shift + F7 shortcut.
Select the form in the designer then go to the Properties Window and find the Events button. It is
represented by a thunderbolt icon. If it is not visible, be sure that a control is selected in the Designer.
The Properties Window will now show a list of events for the selected control in the Designer. Find
the Load event of the form. Clicking the combo box beside it will show you the list of valid methods for the
event that exist in the code of the form. You can then choose which method to attach to this event. We
can also create a new event handler by double clicking the selected event in the Properties Window. You
will be taken to the Code Editor with the proper event handler created for you. Add the highlighted code.
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "Text changed by the Load event";
}
This statement will modify the Text property of button in the form. The Load event of the form occurs once
the form is finished loading. So when you run the program once more, as soon as the program has finished
loading, the text inside the button will be changed.
You have now successfully created an simple event-driven windows forms application using the tools
available in Visual Studio and Visual C# Express.
Event Handling
Graphical user interfaces in .NET and Visual C# uses event handling mechanism to handle events that
occur while the program is running. Events are behaviors or happenings that occur when the program is
running. Event handling is the process of monitoring for certain events to occur, and then executing
codes when a specific event happens. Windows forms use event handling to add functionality and respond
with the user. Without event-handling, forms and user interfaces are pretty much useless. This tutorial
assumes that you already learned the concepts of delegates and events.
Events are declared using a delegate as a type. Delegates hold references to methods. The following is an
example of declaring a delegate and an event.
public delegate void SampleEventHandler(int);
We will now add event handling to the event. Event handlers are methods that match the delegate type
of the event and the ones that will be executed when the event occurs. Event handlers are attached to an
event. Attached event handlers are executed when the event occurs. You can attach multiple event handlers
to the event and they will all run when the event occurs. To attach an event handler to an event, you first
create it. When creating an event handler, be sure that it matches the signature of the delegate that the
event uses. For example, considering the delegate created above which has a return type of
an
void and
int parameter, our event handlers should also have a void return type, and an int parameter
To activate the event, we call it passing the required arguments the same way we call methods.
SampleEvent(3);
EventHandler delegate.
As you can see with the definition of the delegate, it has no return type and has two parameters,
an
object, and an EventArgs instance. The object sender represents the control that activates the
event. We will demonstrate its use later. The second argument is an instance of the
EventArgs class.
This can be called as the event argument and they contain data about the event that happened.
The
EventArgs is actually a base class and contains no useful members. Certain events will have event
EventArgs and contain useful properties that the event handler can
use. You will notice that the created event handler by Visual Studio matches the signature of
the
EventHandler.
If you want to create event handlers manually, then be sure to follow the signature of the delegate type
of the event. Visual Studio proposes a naming convention for event handlers, as seen in the generated
event handler. When naming event handlers, type the name of the control(specified by its
Name property)
followed by an underscore and then the name of the event. You can ignore this convention if the event
handler will be used by multiple events as we will see later.
EventHandler delegate has two parameters, and the first of them is an object
which represents the control that sent the event. Since it is of type
of the event because every control is derived from the
to an object, we need to convert it back to the proper control to access its useful properties. To demonstrate
its use, add a button to the form. Change the
Click event also has a type ofEventHandler. Use the following code for the event handler.
Run the program and click the button. A message box will be shown telling the text inside the button that
sent the Click event.
The first line of the event handler converts the sender object to a
its
Text property. We then call the Show method of the MessageBox class to show the value of the
Event Arguments
The second parameter which actually varies depending on the event is an event argument. The most
common is the
EventArgs which is the base class of event arguments. It has no properties you can use
in your event handler. To demonstrate an event that has a different event argument, we will use the
MouseClick event of the button which is a better version of the Click event. Since it is not the default event,
we can access it in the events section of the Properties Window. Be sure that the button is selected in the
designer. Click the thunderbolt icon to show the events of the button. We need to remove the
handler first so it will not conflict with theMouseClick event. Find the
next to it. Then find and double-click the
delegate
ordinary
is
type
of
Click event
MouseEventHandler.
It
has
the
same
signature
as
the
EventHandlerdelegate, but it has a different type for its event argument which
properties such as which button(left or right) of the mouse is clicked, the number of clicked done, how
much the mouse wheel was rotated, and the point location of the click relative to the source control. Use
the code below for the
The code above uses the event argument parameter to access the x and y coordinates of the point where
the mouse was clicked. The output below my vary depending on where you click on the button.
There are many more event argument types and each offers useful properties about the event that took
place.
The top combo box is used to select controls in the Designer. This is useful when you can't select certain
controls because they aren't visible or very small.
Find the desired event. To attach an event handler to an event, you can double-click the name of the event
to generate an event handler for the specified event. Alternatively, if you already have created event
handlers, you can click the dropdown button to view all the valid event handlers that match the signature
of the delegate type of the specified event.
where FormName is the name of the form, for example, Form1. A third file with .resx extension is used
for resources of the form and will be discussed in a separate lesson. When we create the form, add controls,
and modify properties, all the code is written in a somewhat hidden file with a .Designer.cs extension. If
you can't see it, find the .cs file for the form in the Solution Explorer and click the arrow button beside it.
Double-clicking that file will allow you to see all the codes that were generated by Visual Studio. The code
contains methods for disposing and initializing the controls. You can see the controls being declared and
properties, such as Location and Text, are set depending on what you specified in the Properties Window.
You will also see event handlers being attached to events of controls. If you can't see the code, it is hidden
by default and is labeled "Windows Forms Designer generated code". Just click the plus icon to its left to
show it. You will see that the code for initializing the controls and their properties and events is located
inside a method called InitializeComponent. This method is called in the form's constructor located at
the main code file for the form's class. The codes in the Designer file is initially hidden because Visual
Studio want's you to use the Designer and the Properties Window instead of writing all these codes
manually.
You can also specify the title of the message box by using another overloaded version of the Show method.
MessageBox.Show("Hello World!", "A Message");
You can also change the buttons that will be shown in the message box if you don't want to use the default
OK button. You can do this by using the System.Windows.Forms.MessageBoxButtons enumeration.
MessageBox.Show("Hello World!", "A Message", MessageBoxButtons.OKCancel);
Buttons Shown
AbortRetryIgnore
OK
OK
Member
Buttons Shown
OKCancel
OK, Cancel
RetryCancel
Retry, Cancel
YesNo
Yes, No
YesNoCancel
The Show() method returns a value from the System.Windows.Forms.DialogResult enumeration. This
is useful to determine what button you pressed in the message box. For example, if you click the "Yes"
button in the message box, then the Show() method will return the value DialogResult.Yes.
DialogResult result;
result = MessageBox.Show("What is your choice?");
if (result == DialogResult.Yes)
{
//You pressed the Yes button
}
if (result == DialogResult.No)
{
//You pressed the No button
}
Please
note
that
also
has
a DialogResult property.
This
is
not
the System.Windows.Forms.DialogResult.
You can also add an icon for your message box to further imply the purpose of the message. You do this
by using the members of theMessageBoxIcon enumeration.
MessageBox.Show("Hello World!", "A Message",
MessageBoxButtons.OK, MessageBoxIcon.Information);
The table below shows the different icons that you can use for your message box.
Icon
Member
Usage
Asterisk
Information
Error
Hand
Stop
Exclamation
Warning
Question
You can use the MessageBoxIcon.None to indicate that the message box will have no icon.
The MessageBoxDefaultButton enumeration tells which of the button is the default, that is, the one that
is pressed when the enter key in the keyboard is pushed. It has only 4 members which
are Button1, Button2, Button3, Button4. For example, in a message box that has an OK and a Cancel
buttons, using MessageBoxDefaultButton.Button1 will make the OK button as the default. When the
message box is shown and you pressed Enter in the keyboard, the OK button is pressed.
MessageBox.Show("Hello World!", "A Message",
MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button1);
Properties
Description
Anchor
Specifies how the control relocates and resizes whenever the form
is resized.
AutoSize
If set to true, the control will automatically size itself to fit the
contents.
BackColor
BackgroundImage
BackgroundImageLayout
Bottom
Gets the distance in pixel between the top of the control's container
and the bottom of the control.
CausesValidation
ContextMenuStrip
Controls
Dock
Enabled
Tells whether the user can interact with the control. Set to false to
disable the control.
ForeColor
The foreground color of the control. This is also the font color of
the text inside the control.
Height
Left
Gets or sets the distance between the left edge of the control and
the left edge of its container.
Location
Locked
MaximumSize
Margin
MinimumSize
Name
Padding
Parent
Right
The distance between the right edge of the control and the left
edge of its container.
Size
TabIndex
Specifies the number of the control in the tab order of its container.
TabStop
Tag
Text
TextAlign
Top
The distance between the top edge of the control and the top edge
of its container.
Visible
Width
Controls
Controls are visual components that compose the graphical user interface. Everything you see in a GUI is
a control, including the form itself. Controls are located at the Toolbar grouped inside different categories.
Most of the controls inherit from theSystem.Windows.Forms.Control base class which exposes several
properties, methods, and events common to those controls.
Control Properties
The following are some of the useful properties of the Control class.
Figure - Control Properties
The most important property in the table is the Name property. This property allows you to reference the
control in code. The following discusses more properties common to most of the controls.
The System colors the colors your operating system uses as default colors for controls. The Web tab shows
colors that are safe to use for the web. And the Custom tab shows much more colors. Alternatively, you
can type the RGB values of the color separated by commas in the text box next to the property.
You will be presented with a window which allows you to choose a resource. For now, choose local resource
and browse for an image by clicking the Import button.
Once you choose an image, click OK. The background image will now show up on the form. The alignment
and size of an image may not be what you desired. There is another property called
the BackgroundImageLayout property.
It
accepts
values
from
theSystem.Windows.Forms.ImageLayout enumeration.
Value
Description
None
The image will be positioned using its top left corner with no resizing of the image.
Tile
If the image is smaller than the client area of the control, the image will be repeated until it
fills the form.
Center
Stretch
The image will be resized to fit the client area of the control.
Zoom
The image will be fitted to the client area of the control without losing its aspect ratio.
Most of the time, Stretch will work fine. The form below has a background image with an image layout
of Stretch.
can
change
the
font
type,
color,
size,
and
style
of
the Font and ForeColor properties. Let's use a button control as an example.
the
control
by
using
To change different font properties of the control, find the Font property in the Properties Window. You
will notice a drop down button in its left. Open it up and more properties about the font will be exposed.
The useful once are the Name, which defines the type of font to use, the Size which indicates the size of
font, Unit which
tells
the
unit
to
use
for
the
size
of
the
font,
and Italic, Strikeout, Underline and Bold to add styles to the control. Alternatively, you can use the
button to the right of the font property to open the Font Window.
Here, you can choose the font type, the font style, the size and add certain effects. You can even see a
preview of the font. With these, you can customize the font of the controls.
Event
Description
BackColorChanged
BackgroundImageChanged
Click
Occurs when you click the control with the left mouse button.
ControlAdded
ControlRemoved
DoubleClick
DragDrop
EnabledChanged
Enter
FontChanged
ForeColorChanged
GotFocus
KeyDown
Occurs when a key in the keyboard is pressed while the control has
the focus.
KeyPress
Occurs when the key in the keyboard is pressed and released while
the control has the focus.
KeyUp
Leave
LostFocus
MouseClick
MouseDoubleClick
MouseDown
Occurs when a button in the mouse is down while inside the control.
MouseEnter
MouseHover
MouseLeave
MouseMove
Occurs when the mouse pointer moves while inside the bounds of the
control.
MouseUp
MouseWheel
Occurs when you move the mouse wheel while the control has the
focus.
Move
Paint
ParentChanged
Resize
TextChanged
Validated
Validating
VisibleChanged
may change. For example, when we disable a button (setting its Enabled property to false), its color and
appearance will change. Note that the change is only visible when you run the form and not in the designer.
When a control is disabled, it will not receive focus or events. For example, if a button is disabled, you
cannot click it.
form and not in the designer. This allows you to still select the control in the designer even if the Visible
property is set to false.
More about the properties and features of controls will be discussed in the following lessons.
Control Events
The following table shows the some useful events common to most controls.
We will discuss most of the events above in later chapters.
Control Methods
The following are the most useful methods of the Control class.
Methods
Description
BringToFront
Contains
CreateControl
FindForm
Focus
GetContainerControl
Hide
Refresh
Forces the control to invalidate its client area and immediately redraw itself and any child cont
Select
SendToBack
Show
Update
Causes the control to redraw the invalidated regions within its client area.
The Control class also offers some methods that allow you to manually trigger events of the control. Such
methods starts with Onfollowed by the name of the event. For example, the OnClick event triggers the
Click event when called. Note that some events cannot be triggered by user interaction such as
the Paint event. If you want to trigger such events, use the methods offered by the Control class. You
will learn more about these methods when we delve deeper into the world of C#.
Note that these properties, events, and methods are inherited by most of the controls thanks to inheritance.
Therefore, I may not include them again when I present the properties, events, and methods of individual
controls unless they are very significant to the control.
Scenario
Name
for
obtaining
personal formPersonalInformation,
personalInformationForm,
frmPersonalInformation
The following lessons use the first naming convention where you simply use the name of the control in
camelCasing style followed by a descriptive name. You don't have to memorize a set of abbreviations or
invent one. When you drag a control from the ToolBox, you simply need to remove the number suffix and
add a descriptive name. When you are typing and you want to easily find what control you want to work
with, simply type what kind of control it is, for example, a text box, and all the text box controls will show
up in the IntelliSense. The only downside is some names might become too long. It is still up to you as to
what naming convention you are more comfortable to use.
The following gives you some example name depending on the control and its use.
It is not necessary to name every control in the form. Controls that will never be accessed in code can be
left by their default name. Examples of these are the labels that are merely used to label other controls.
Have a habit of naming the control after you place them onto the form.
Property
Description
AcceptButton
The button on the form that is pressed when you hit the Enter key.
CancelButton
The button on the form that is pressed when you hit the Esc key.
ClientSize
Gets or sets the client area of the form. The client area is the portion of the form inside
the frame borders.
ControlBox
Specifies whether to show the control box at the top right portion of the form. The control
box contains the buttons minimize, maximize, and close.
Controls
DesktopBounds
Font
The font that the form will use. Controls inside the form will inherit this property.
Shows a help button right before the close button of the form. (minimize and maximize
buttons should be disabled)
Icon
Location
MainMenuStrip
MaximizeBox
Tells whether the maximize box located at the top right is displayed.
MinimizeBox
Tells whether the minimize box located at the top right is displayed.
Modal
Name
OwnedForms
Owner
ShowIcon
Tells whether the icon is displayed at the left side of the caption bar.
Size
StartPosition
Text
At the top, you will find the Caption Bar. The Caption Bar is composed of the icon, the caption, and the
control box. The control box contains buttons such as minimizing, maximizing, closing, or a help button.
The Client Area is where we
add the controls. The border or frame, which includes the caption
bar,encloses the client area and allows you to resize the form.
The following are some of the useful properties of the Form base class.
Figure 1
Method
Description
Activate
AddOwnedForm
CenterToScreen
Close
Hide
OnLoad
Show
Figure 2
Description
Activated
Click
Deactivated
FormClosed
FormClosing
Occurs when the form is closing. Allows you to halt the closing of the form.
HelpButtonClicked
KeyPress
Load
MenuComplete
MenuStart
ResizeBegin
ResizeEnd
Shown
Figure 3
The Form class is a child of the System.Windows.Forms.Control base class so the methods and
properties from the Control class are also available in the Form class.
maximizing of control or you want to only close the form through the code. The
image below shows you how the form will look when you set ControlBox property to false.
If you want to disable only the minimize or the maximize button, then you can use
the MinimizeBox and MaximizeBox and set them to false.
The form above has its minimize and maximize box hidden. Unfortunately, you cannot hide only the close
button.
property
to
values
of
Description
None
FixedSingle
Fixed3D
FixedDialog
Sizable
FixedToolWindow
SizableToolWindow
The form has a thick, non-resizable, dialog style border that has no minimize
or maximize boxes.
The default. The form has a resizable border.
The form has a non-resizable border that has only a close button. This style is used for
tool windows.
Same as FixedToolWindow but resizable.
None
FixedSingle
Fixed3D
FixedDialog
Sizable
FixedToolWindow
SizableToolWindow
Form Icons
We use the Icon property to change the icon displayed at the upper left side of the form. Click the browse
button next the Icon property in the Properties Window and find the .ico file which is the file extension
for an icon image. The ShowIcon property allows you to hide or show the icon in the caption bar.
that using the AcceptButton andCancelButton properties. If a button is an accept button, whenever the
user hits Enter while the form is active, that button's Clickevent will be executed. The Cancel button is
activated whenever the Escape key is pressed. Just go to the Properties Window, find the desired property
and click the drop down button. You
will be presented with the names of all the button control in the
form. Choose the desired button. For example, suppose you are creating a login form. You can
set the
button used for logging in as the Accept button. This way, the user can simply press Enter when he is
finished typing the password.
There are many more to discover on windows forms and they will be discussed in later lessons.
Description
AutoSize
Specifies whether the button will automatically resize to fit its content.
FlatStyle
Determines the style of the button. Popup makes the button flat, and when you hover
on the button, the button will pop out. Flat makes the button flat and when you move
point your mouse inside the button, the background color of the button changes.
Enabled
Image
ImageAlign
Text
Visible
Event
Description
Click
Enter
Leave
Occurs
when
inactive anymore.
LocationChanged
Occurs
when
the
button is changed.
MouseDown
MouseEnter
MouseHover
MouseUp
MouseLeave
Occurs
when
leaves the button.
the
the
becomes
control
location
mouse
the
becomes
of
the
stationary
pointer
A button is still useless by just editing its properties. It needs to react to events to do some work. The
following are the most common events available for the Button control.
You have already seen the Click event which is the default event for a button. Let's create another
application that demonstrates the use of other events. Create a new form and drag a button to the form
from the toolbox. It's not important what text you put for the button. In the properties window, find
the Name property and change its value to buttonSample. We will now refer to that button in the code
using that name. Our program will demonstrate the MouseEnter and MouseLeave events. To access these
events, the easiest way is to go to the properties window and click the button with the lightning symbol.
After typing the code, return back to the Properties Window and now choose the MouseLeave event and
double click it to generate an event handler. Again, type the highlighted code inside the event handler
method.
private void buttonSample_MouseLeave(object sender, EventArgs e)
{
btnSample.Text = "Mouse has left!";
}
Now run the program. Roll over your mouse to the button and notice that the text has changed. Take away
the mouse pointer from the button and the text of the button will change again.
Property
Description
AutoSize
BorderStyle
Font
Text
TextAlign
properties
of
the
The Text property is the most important one because the main purpose of the Label control is to show text
in the form.
There are events that are also available for the Label control, but most of the time, you won't be needing
them.
Property
Description
AcceptsReturn Used with Multiline. Tells if whether the return key is included in the input. The
return will be converted into a \n escape sequence.
AcceptsTab
Indicates whether to accept tab as an input. By default, hitting tab will bring the focus
to the control with the next TabIndex in the form.
Enabled
Set to false to make the text box read-only therefore making the text box act like a
label.
Font
Lines
Multiline
Text
PasswordChar
Accepts a character that will be used to mask each character typed by the user.
ReadOnly
Visible
WordWrap
The TextBox control (System.Windows.Forms.TextBox) is the most basic means of input in a windows
forms. You give the input data by typing it inside the text box. The text you type can be accessed by using
the Text property of the control. The following table shows some useful properties that you can use for
the TextBox control.
Figure 1
The following example shows the use of text boxes. Create a new Windows Application project. The
program will ask two numbers and then when a button is pressed, the sum is shown using a label. Drag
two textboxes to the form and name them textBoxFirstNumberand textBoxSecondNumber. Also drag
one label for each text box indicating their purpose. Drag another label that will be used to show the sum
and name it labelSum. Place a Button control and name it buttonAdd. Adjust the position and sizes of the
controls to match the layout below.
Double-click the button to add an event handler to its click event. Type the following codes.
private void buttonAdd_Click(object sender, EventArgs e)
{
The code converts the contents of textBoxFirstNumber and textBoxSecondNumber into integers using
the Parse method of the Int32class and stored them in their respective variables. We require conversion
because the Text property is of type string. Their contents are accessed using the Text property. The
sum is then determined. The sum is displayed afterward by assigning it to the Text property oflabelSum.
The most useful event of the TextBox is the TextChanged event which occurs when the text inside the
textbox is modified. The following program shows an example of using this event.
Create another windows forms application and add a textbox and a label in the form. Name them you can
leave their default names right now.
Delete the text of label1 by removing the content of its Text property. Note that it would be hard to
select this label now if the AutoSizeis set to false so you can select this label using the top combo box of
the Properties Window. The default event of the TextBox control is the TextChanged event so double
clicking it will create an event handler for the said event. Add the following code to the event handler.
private void textBox1_TextChanged(object sender, EventArgs e)
{
label1.Text = textBox1.Text;
}
Now run the program and type anything in the text box. Notice that the text of the label copies the text
you type in the text box.
When the text inside the textbox is modified, the event handler executes and copies the text inside textbox1
to label1.
By default, a text box can only handle a single line of text. To make it a multiline textbox, simply set
the Multiline property to true. Once you do that, you will notice that you can change the height of the
textbox in the designer.
You can set the WordWrap property to true to automatically bring the cursor below when it reaches the
right edge of the text box. If it is set to false, the text will continue to the to the right clipping the ones at
the left side. You can set the ScrollBar property to Horizontal,Vertical or Both to add scroll bars to
a multiline text box. When using a multiline textbox, you can use the Lines property to retrieve the
individual lines of text.
If your textbox is expected to accept passwords, then you must set the PasswordChar to something
like * to mask each character type in the textbox by the character indicated in the PasswordChar property.