Professional Documents
Culture Documents
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.
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.
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.
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.
ToString Returns a String containing the name of the Component, if any. This method
should not be overridden.
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.
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.
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.
Property Description
Autosize Gets/Sets the control to automatically resized to display all its contents.
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.
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.
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.
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
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.
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
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
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.
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.
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
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.
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;
}
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.
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.
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: OthersLabel
Text: <empty>
Name: SpecifyTextBox
Text: <empty>
Name: SubmitButton
Text: &Submit
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;
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