You are on page 1of 14

Working with Controls

In this lesson, we shall build an initial interface by customizing the default form. We will be adding
controls to the form. Among the controls, the most common ones are button, label, text box, list box,
combo box, picture box, check box, radio and more. The controls can be made visible or invisible at
runtime. However, some controls will only run in the background and cannot be seen at runtime, one
such control is the timer. More so, we will learn how to work with some common controls and write
codes for all the controls so that they can interact with events triggered by the users.

After completing this lesson, you will be able to:


 Describe the basic controls.
 Add controls to a form,
 Set controls properties design time and programmatically at run time.
 Write some codes for the common controls.
 Subscribe to and process events exposed by Windows Forms and controls.

The Event Driven Programming Concept


Event-driven programming means that a user will decide what to do with the program, thus, we need
to write code to response to certain events triggered randomly by the user via the controls on the form.
These events do not occur in a certain order.

Event Icon

Every object (form and control) has a set of related events. An event is
an incident that happens to the object/control due to the action triggered
randomly by the user, such as but not limited to clicking or pressing a
key, drag and drop, and more.

Figure 2.1 Properties Window with the Events icon On

Basic Control Objects


A control object is a user interface element created on a form by using a toolbox. In fact, the form
itself is an object. Every Visual C# control consists of three important elements:

1. Control Properties
Properties describe the object. All the Visual C# objects can be moved, resized or customized by setting
their properties. A property is a value or characteristic held by an object, such as Size or Fore Color.
Properties can be set at design time by using the Properties window or at run time by using statements
in the program code.
Object.Property = Value Example: Form1.Text = "Hello";
Where
 Object is the name of the object you're customizing.
 Property is the characteristic you want to change.
 Value is the new property setting.

Refer to Microsoft documentation for a complete list of properties associated with different controls
and restrictions.

2. Control Methods
A method is a procedure created as a member of a class and they cause an object to do something.
Methods are used to access or manipulate the characteristics of an object or a variable.

For example, the MessageBox control has a public method named Show() that is called.
MessageBox.Show("Hello, World")
3. Control Events
An event is a signal that informs an application that something important has occurred and what
happens when an object does something. A class has events as it creates instant of a class or an object.
For example, when a user clicks a control on a form, the form can raise a Click event and call a
procedure that handles the event. There are various types of events associated with a Form like click,
double click, close, load, resize, etc. Following is the default structure of a form Load event handler
procedure.
private void Form1_Load(object sender, EventArgs e)
{
/*code here */
}
Form1_Load() method handles Load event. It does nothing other than loading an empty form. To
make the load event does something such as if you want to initialize some variables like properties,
etc., then you will keep such code inside Form1_Load() event handler.

Common Controls Methods, Events and Properties


Visual C# provides a huge variety of controls to create rich user interface. Functionalities of all these
controls are defined in the respective control classes in the System.Windows.Forms namespace.

The Toolbox is usually hidden when you start, you need to click View on the menu bar and then select
Toolbox to reveal the toolbox. You can also use shortcut keys Ctrl+W+X to bring out the toolbox. You
can position the toolbox by dragging it anywhere you like while its status is set to float. You can also
dock the toolbox by right-clicking on the tool box and choose dock from the pop-up menu.

The Button Control


The Button control represents a standard Windows button. It is generally used to generate a Click
event by providing a handler for the Click event.

Commonly Used Properties of the Button Control


Property Description

BackColor Gets/Sets the background color of the control.

BackgroundImage Gets/Sets the background image displayed in the control.


DialogResult Gets/Sets a value that is returned to the parent form when the button is clicked.
This is used while creating dialog boxes.
ForeColor Gets/Sets the foreground color of the control.
Image Gets/Sets the image that is displayed on a button control.
TabIndex Gets/Sets the tab order of the control within its container.
Text Gets/Sets the text associated with this control.

Commonly Used Methods of the Button Control


Method Name Description

Select Activates the control.

ToString Returns a String containing the name of the Component, if any. This method
should not be overridden.

Commonly Used Events of the Button Control


Event Description
Click Occurs when the control is clicked.

DoubleClick Occurs when the user double-clicks the Button control.


GotFocus Occurs when the control receives focus.

TabIndexChanged Occurs when the TabIndex property value changes.


TextChanged Occurs when the Text property value changes.

Validated Occurs when the control is finished validating.


private void DisplayButton_Click(object sender, EventArgs e)
{
MessageBox.Show("You Click A Button", "Message", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}

private void ExitButton_Click(object sender,EventArgs e)


{
this.Close();
}
Clicking the Display button, displays a MessageBox.

The TextBox Control


The text box is the standard control for accepting input from the user as well as to display the output.
It can handle string (text) and numeric data but not images or pictures. String in a text box can be
converted to a numeric data by using a function. By default, it takes a single line of text, however, you
can make it accept multiple texts like the RichTextBox and even add scroll bars to it .

See also the RichTextBox control that goes further than the TextBox control by providing features like
text editing and formatting.

See also the MaskedTextBox that provides the user restrictions through masking of the values.

Properties of the TextBox Control


Property Description
Font Gets/Sets the font of the text displayed by the control.

ForeColor Gets/Sets the foreground color of the control.


Multiline Gets/Sets a value (True/False) indicating whether this is a multiline TextBox
control. When creating multiline TextBoxes, you will most likely have to set one
or more of the MaxLength, ScrollBars, and WordWrap properties in the
Properties window.

MaxLength Set to a specific value in data-entry applications, which prevents users from
entering more characters than can be stored in a database field.

PasswordChar Gets/Sets the character used to mask characters of a password in a single-line


TextBox control. The default value of this property is an empty string. The user
can’t copy or cut the text on the control.

ReadOnly Gets/Sets a value indicating whether text in the text box is read-only.
ReadOnly prevents users from editing.
TabIndex Gets/Sets the tab order of the control within its container.

TextAlign Gets/Sets how text is aligned in a TextBox control.

Text Gets/Sets the current text inside the TextBox.


WordWrap Determines whether the text is wrapped automatically when it reaches the
right edge of the control. The default value is True.

Commonly Used Methods of the TextBox Control


Method Description

AppendText Appends text to the current text of a text box.

Clear Clears all text from the text box control.


ResetText Resets the Text property to its default value.
ToString Returns a string that represents the TextBoxBase control.
Undo Undoes the last edit operation in the text box.

Events of the TextBox Control


Event Description

Click Occurs when the control is clicked.

DoubleClick Occurs when the control is double-clicked.


TextAlignChanged Occurs when the TextAlign property value changes.

private void MessageButton_Click(object sender, EventArgs e)


{
MessageBox.Show(“Name: " + NameTextBox.Text + "\nCourse :" + CourseTextBox.Text)
}
When the above code is executed and run, it will show Clicking the Display button would show the following
message box:
the following window:
The Label Control
The label is a very useful control as it is not only used to provide instructions and guides to the users,
it can also be used to display outputs. It is different from text box because it can only display static
text, which means the user cannot change the text.

Property Description

Autosize Gets/Sets the control to automatically resized to display all its contents.

BorderStyle Gets/Sets the border style for the control.


FlatStyle Gets/Sets the flat style appearance of the Label control

Font Gets/Sets the font of the text displayed by the control.


ForeColor Gets/Sets the foreground color of the control.

Text Gets/Sets the text associated with this control.


TextAlign Gets/Sets the alignment of text in the label.

Commonly used Methods of the Label Control


Method Description

Refresh Forces the control to invalidate its client area and immediately redraw itself and any
child controls.
Select Activates the control.
Show Displays the control to the user.

ToString Returns a String that contains the name of the control.

Commonly Used Events of the Label Control


Event Description

Click Occurs when the control is clicked.

DoubleClick Occurs when the control is double-clicked.


GotFocus Occurs when the control receives focus.
LostFocus Occurs when the control loses focus.

TextChanged Occurs when the Text property value changes.

private void Form1_Load(object sender, EventArgs e)


{ // Set window width and height
this.Height = 300;
this.Width = 560;
this.Text = "Label Demo";//Set the caption bar text of the form.
this.HelpButton = true; //Display a help button on the form.
}

private void Label1_Click(object sender, EventArgs e)


{
Label1.Location = new Point(50, 50);
Label1.Text = "You have just moved the label";
}

private void Label1_DoubleClick(object sender, EventArgs e)


{
Label Label2=new Label();
Label2.Text = "New Label";
Label2.Location = new Point(Label1.Left, Label1.Height + Label1.Top + 25);
this.Controls.Add(Label2);
}
Clicking and double clicking the label would produce the following effect:

List Box
The ListBox represents a Windows control to display a list of items to a user. A user can select an item
from the list. It allows the programmer to populate the list box items at design time by using the
properties window or at the runtime.

To add items to a ListBox, get to the properties window of this control. Click the ellipses (...) button
next to the Items property. This opens the String Collection Editor dialog box, where you can enter the
values one at a line.
Commonly Used Properties of the ListBox Control
Property Description
BorderStyle Gets/Sets the type of border drawn around the list box.
ColumnWidth Gets/Sets the width of columns in a multicolumn list box.

HorizontalExtent Gets/Sets the horizontal scrolling area of a list box


HorizontalScrollBar Gets/Sets the value indicating whether a horizontal scroll bar is displayed in
the list box
Items Gets the items of the list box.
MultiColumn Gets/Sets a value indicating whether the list box supports multiple columns.

SelectedIndex Gets/Sets the zero-based index of the currently selected item in a list box.
SelectedIndices Gets a collection that contains the zero-based indexes of all currently selected
items in the list box.
SelectedItem Gets/Sets the currently selected item in the list box.
SelectedItems Gets a collection containing the currently selected items in the list box.

SelectedValue Gets/Sets the value of the member property specified by the ValueMember
property.
SelectionMode Gets/Sets the method in which items are selected in the list box. This property
has values:
 None
 One
 MultiSimple
 MultiExtended

Sorted Gets/Sets a value indicating whether the items are sorted alphabetically.
Text Gets or searches for the text of the currently selected item in the list box.

Commonly Used Methods of the ListBox Control


Method Description
ClearSelected Unselects all items in the ListBox.
FindString Finds the first item in the ListBox that starts with the string specified as an
argument.
FindStringExact Finds the first item in the ListBox that exactly matches the specified string.

GetSelected Returns a value indicating whether the specified item is selected.


SetSelected Selects or clears the selection for the specified item in a ListBox.
Commonly used events of the ListBox Control
Event Description
Click Occurs when a list box is selected.
SelectedIndexChanged Occurs when the SelectedIndex property of a list box is changed.

In this example, we will fill up a list box with items, retrieve the total number of items in the list box,
sort the list box, remove some items and clear the entire list box.
Name:Label1
Text:Wish List
Name: WishListBox Name: FillButton
Text:Fill

Name: SortButton
Name: SelectionLabel Text:Sort
Text:<empty>
AutoSize: False Name: RemoveButton
Text:Remove

Name:Label2 Name: ClearButton


Text:Selection Text:Clear

Name:Label3 Name: CountLabel Name: CountButton


Text:Count Text:<empty> Text:Count
AutoSize: False

private void Form1_Load(object sender, EventArgs e)


{
//creating multi-column and multiselect list box
WishListBox.MultiColumn = true;
WishListBox.SelectionMode = SelectionMode.MultiExtended;
}
//populates the list
private void FillButton_Click(object sender, EventArgs e){
WishListBox.Items.Add("Safety");
WishListBox.Items.Add("Security");
WishListBox.Items.Add("Education");
WishListBox.Items.Add("Health");
WishListBox.Items.Add("Peace");
WishListBox.Items.Add("Liberty");
}
//sorting the list
private void SortButton_Click(object sender, EventArgs e){
WishListBox.Sorted = true;
2 - Working with Controls 7
}
//clears the list
private void ClearButton_Click(object sender, EventArgs e)
{
WishListBox.Items.Clear();
}
//removing the selected item
private void RemoveButton_Click((object sender, EventArgs e){
WishListBox.Items.Remove(WishListBox.Text);
}
//counting the number of items
private void CountButton_Click(object sender, EventArgs e)
{
CountLabel.Text = Convert.ToString(WishListBox.Items.Count);
}
//displaying the selected item on the third label
private void WishListBox_SelectedIndexChanged(object sender, EventArgs e)
{
SelectionLabel.Text = WishListBox.Text;
}
ComboBox
The ComboBox control is used to display a drop-down list of various items. It is a combination of a text
box in which the user enters an item and a drop-down list from which the user selects an item.

The combo box control has many of the properties, methods, and events of a listbox control, but it
does not have BorderStyle, ColumnWidth, ScrollAlwaysVisible, SelectionMode, HorizontalExtent and
HorizontalScrollBar properties.
Commonly Used Properties of the ComboBox Control
Property Description
DropDownHeight Gets/Sets the height in pixels of the drop-down portion of the combo box
DropDownStyle Gets/Sets a value specifying the display style of the combo box.
DropDownWidth Gets/Sets the width of the drop-down of a combo box
FlatStyle Gets/Sets the appearance of the ComboBox.
Items Gets an object representing the collection of the items contained.
MaxDropDownItems Gets or sets the maximum number of items to be displayed.
MaxLength Gets/Sets the maximum number of characters a user can enter in the editable
area of the combo box.
SelectedIndex Gets/Sets the index specifying the currently selected item.
SelectedItem Gets/Sets currently selected item.
SelectedText Gets/Sets the text selected in the editable portion of a ComboBox.
SelectedValue Gets/Sets the value of the member property specified by the ValueMember
property.
Text Gets/Sets the text associated with this control.

Commonly Used Methods of the ComboBox Control


Method Name Description

FindString Finds the first item in the combo box that starts with the string specified as an
argument.
FindStringExact Finds the first item in the combo box that exactly matches the specified string.
SelectAll Selects all the text in the editable area of the combo box.
Commonly Used Events of the ComboBox Control
Event Description

DropDown Occurs when the drop-down portion is displayed.

DropDownClosed Occurs when the drop-down portion is no longer visible.


DropDownStyleChanged Occurs when the DropDownStyle property has changed.

SelectedIndexChanged Occurs when the SelectedIndex property of the control has changed.
SelectionChangeCommitted Occurs when the selected item has changed and the change appears in
the combo box.

Fill a combo box with various items, get the selected items in the combo box and show them in a list
box and sort the items.

Name: WishListBox

Name: WishListComboBox

Name: SendButton
Text: >>

Name: FillButton
Text:Fill

Name: SortButton
Name: SelectedItemLabel Text: Sort

Name: ClearButton
Text: Clear

//sends the selected items to the list box


private void SendButton_Click(object sender, EventArgs e)
{
if (WishListComboBox.SelectedIndex > -1)
{
int sindex;
sindex = WishListComboBox.SelectedIndex;
object sitem;
sitem = WishListComboBox.SelectedItem;
WishListBox.Items.Add(sitem);
}
}
//'populates the list
private void FillButton_Click(object sender, EventArgs e )
{
WishListComboBox.Items.Clear();
WishListComboBox.Items.Add("Good Music");
WishListComboBox.Items.Add("Good Books");
WishListComboBox.Items.Add("Roads");
WishListComboBox.Items.Add("Food for all");
WishListComboBox.Items.Add("Shelter for all");
WishListComboBox.Items.Add("Industrialisation");
WishListComboBox.Text = "Select from...";
}
//'sorting the list
private void SortButton_Click(object sender, EventArgs e){
WishListComboBox.Sorted = true;
}
//clears the list
private void ClearButton_Click object sender, EventArgs e)
{
WishListComboBox.Items.Clear();
}
//'displaying the selected item on the label
private void WishListComboBox_SelectedIndexChanged( object sender, EventArgs e)
{
SelectedItemLabel.Text = WishListComboBox.SelectedItem.ToString();
}

Execute the code and click on various buttons to check the actions performed by each.

Picture Box
The PictureBox control is used for displaying images on the form. The Image property of the control
allows you to set an image both at design time or at run time.

Commonly Used Properties of the PictureBox Control


Property Description

Image Gets/Sets the image that is displayed in the control.

ImageLocation Gets/Sets the path or the URL for the image displayed in the control.
SizeMode Determines the size of the image to be displayed in the control. This property
takes its value from the PictureBoxSizeMode enumeration, which has values:
 Normal - the upper left corner of the image is placed at upper left part of the
picture box
 StrechImage - allows stretching of the image
 AutoSize - allows resizing the picture box to the size of the image
 CenterImage - allows centering the image in the picture box
 Zoom - allows increasing or decreasing the image size to maintain the size
ratio.
TabIndex Gets/Sets the tab index value.
TabStop Specifies whether the user will be able to focus on the picture box by using the
TAB key.
Text Gets/Sets the text for the picture box.

Commonly Used Methods of the PictureBox Control


Method Description

Load Displays an image in the picture box


ToString Returns the string that represents the current picture box.

Commonly Used Events of the PictureBox Control


Event Description

Click Occurs when the control is clicked.


Enter Overrides the Control.Enter property.
ForeColorChanged Occurs when the value of the ForeColor property changes.

KeyPress Occurs when a key is pressed when the control has focus.
Leave Occurs when input focus leaves the PictureBox.
LoadCompleted Occurs when the asynchronous image-load operation is completed, been
canceled, or raised an exception.
Resize Occurs when the control is resized.
TextChanged Occurs when the value of the Text property changes.
private void EqualizerPictureBox_Click(object sender, EventArgs e)
{
MusicalNotePictureBox.Visible = true; //Set the image to visibility.
EqualizerPictureBox.Visible =false;
}

Name: MusicalNotePictureBox
Name: EqualizerPictureBox
Image: MusicalNote.png
Image: Equalizer.png
Size Mode: Stretch Image
Size Mode: Stretch Image

private void MusicalNotePictureBox_Click(object sender, EventArgs e){


MusicalNotePictureBox.Visible = false; //Set the image to invisibility.
EqualizerPictureBox.Visible = true;
}
When the application is executed, clicking on the Picturebox results in invisibility of the other
picturebox.

Radio Button
The RadioButton control is used to provide a set of mutually exclusive options. The user can select one
radio button in a group. If you need to place more than one group of radio buttons in the same form,
you should place them in different container controls like a GroupBox control.

Property Description

Checked Gets/Sets a value indicating whether the control is checked. The Checked property
of the radio button is used to set the state of a radio button.
Text Gets/Sets the caption for a radio button.

Commonly Used Event of the RadioButton Control


Event Description

CheckedChanged Occurs when the value of the Checked property changed.


Create a group of radio buttons and use their CheckedChanged events for changing the BackColor and
ForeColor property of the form.

Name : RedRadioButton Name : Form1


Text: Red Text : Demo RadioButton

Name : BlueRadioButton
Text: Blue 2 - Working with Controls 11
Name : MessageLabel
Name : GreeRadioButton Text : My ForeColor Changes !
Text: Green

Double click on the radio buttons and place the code in the opened window.
private void RedRadioButton_CheckedChanged(object sender, EventArgs e)
{
MessageLabel.ForeColor = Color.Red;
}
private void GreenRadioButton_CheckedChanged(object sender, EventArgs e)
{
MessageLabel.ForeColor = Color.Green;
}

private void BlueRadioButton_CheckedChanged(object sender, EventArgs e)


{
MessageLabel.ForeColor = Color.Blue;
}

When the above code is executed: The Color of the text in the label will change.

Checkbox
The checkbox control provides user to make decisions that require selecting a combination of options
from a set of alternatives.

Commonly Used Properties of the Checkbox Control


Property Description
Appearance Gets/Sets a value determining the appearance of the check box.

AutoCheck Gets/Sets a value indicating whether the Checked or CheckedState value and
the appearance of the control automatically change when the check box is
selected.
CheckAlign Gets/Sets the horizontal and vertical alignment of the check mark on the check
box.
Checked Gets/Sets a value indicating whether the check box is selected.

CheckState Gets/Sets the state of a check box.

Text Gets/Sets the caption of a check box.


ThreeState Gets/Sets a value indicating whether or not a check box should allow three
check states rather than two.

Commonly Used Methods of the Checkbox Control


Method Description
OnClick Raises the OnClick event.
Refresh Forces to invalidate the client area.
2 - Working with Controls 12
Commonly Used Events of the Checkbox Control
Event Description
AppearanceChanged Occurs when the value of the Appearance property of the check box is
changed.
CheckedChanged Occurs when the value of the Checked property of the CheckBox control
is changed.
CheckStateChanged Occurs when the value of the CheckState property of the CheckBox
control is changed.

Example. The check boxes will allow the users to choose the sources from which they came to know
about the product. If the user chooses the check box with text "others", then the user is asked to specify
and a text box is provided to give input. When the user clicks the Submit button, an appropriate message
is displayed.

Name: FriendsCheckBox
Text: Friends Name: NewspapersCheckBox
Text: Newspapers

Name: WebsitesCheckBox Name: OthersCheckBox


Text: Websites Text: Others

Name: OthersLabel
Text: <empty>
Name: SpecifyTextBox
Text: <empty>
Name: SubmitButton
Text: &Submit

private void SubmitButton_Click(object sender, EventArgs e){


string str;
str = " ";
if (FriendsCheckBox.Checked ==true) {
str = str + FriendsCheckBox.Text;
str += " ";
}
if (WebsitesCheckBox.Checked == true)
{ str += WebsitesCheckBox.Text;
str += " ";
}
if (NewspaperCheckBox.Checked == true ){
str += NewspaperCheckBox.Text;
str += " ";
}
if (OthersCheckBox.Checked == true){
str = str + SpecifyTextBox.Text;
str = str +" ";
}

if (str != null)
MessageBox.Show("You selected : \n" + str + "\nThank you!","Survey",
MessageBoxButtons .OK ,MessageBoxIcon .Information );

}
private void OthersCheckBox_CheckedChanged(object sender, EventArgs e)
{
OtherLabel.Visible = true;
SpecifyTextBox.Visible = true;

2 - Working with Controls 13


private void Form1_Load(object sender, EventArgs e)
{
OtherLabel.Visible = false;
SpecifyTextBox.Visible = false;
SpecifyTextBox.Multiline = true;

When the above code is executed, it will show the following:

References:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/
www.articles.com
www.akadia.com
www.blackwasp.co.uk
www.bogotobogo.com
www.c-sharpcorner.com
www.codeproject.com
www.completechsarptutorial.com
www.csharp-sation.com
www.chsarp.net-tutorials.com
www.develop.com
www.geom.ulcc.edu
www.Indiabix.com
www.tutorialspoint.com
www.w3schools.com

You might also like