0% found this document useful (0 votes)
15 views27 pages

Worksheet GUI1

This document provides a step-by-step guide on creating a new project in C# using Visual Studio, including how to add and manipulate various controls such as Labels, Buttons, TextBoxes, RadioButtons, ComboBoxes, and ListBoxes. It covers the properties and events associated with these controls, along with example code snippets for implementation. The document serves as a comprehensive resource for beginners to understand the basics of Windows Forms application development in C#.

Uploaded by

Dawit Tekie
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views27 pages

Worksheet GUI1

This document provides a step-by-step guide on creating a new project in C# using Visual Studio, including how to add and manipulate various controls such as Labels, Buttons, TextBoxes, RadioButtons, ComboBoxes, and ListBoxes. It covers the properties and events associated with these controls, along with example code snippets for implementation. The document serves as a comprehensive resource for beginners to understand the basics of Windows Forms application development in C#.

Uploaded by

Dawit Tekie
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

How to create a new project in C# ?

Open your Visual Studio Environment and Click File->New Project

Then you will get a New Project Dialogue Box asking in which language you want to create a new project.

Select Visual C# from the list, then you will get the following screen.

Now you can add controls in your Form Control.

How to add controls to Form ?

In the left side of the Visual Studio Environment you can see the Tool Box. There are lots of controls grouping
there in the Tool Box according to their functionalities. Just click the + sign before each group then you can
see the controls inside the group. You can select basic controls from Common Controls group. You can place
the control in your Form by drag and drop the control from your toolbox to Form control.

How to drag and drop controls ?

In the above picture we drag and drop the Button control from Toolbox - Common control to Form control.

Now you can start write codes on each control to create your programs. From the following lessons you can
study how to use these Windows Forms Controls in your C# applications.

C# Label Control

Labels are one of the most frequently used C# control. We can use the Label control to display text in a set
location on the page. Label controls can also be used to add
descriptive text to a Form to provide the user with helpful
information. The Label class is defined in the
[Link] namespace.
Add a Label control to the form - Click Label in the Toolbox and drag it over the forms Designer and drop it in
the desired location.

If you want to change the display text of the Label, you have to set a new text to the Text property of Label.

[Link] = "This is my first Label";

In addition to displaying text, the Label control can also display an image using the Image property, or a
combination of the ImageIndex and ImageList properties.

[Link] = [Link]("C:\\[Link]");

The following C# source code shows how to set some properties of the Label through coding.

using System;
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
[Link] = "This is my first Lable";
[Link] = [Link];
[Link] = [Link];
} } }

C# Button Control

Windows Forms controls are reusable components that encapsulate user


interface functionality and are used in client side Windows applications. A
button is a control, which is an interactive component that enables users to
communicate with an application. The Button class inherits directly from the
ButtonBase class. A Button can be clicked by using the mouse, ENTER key, or
SPACEBAR if the button has focus.

When you want to change display text of the Button , you can change the Text property of the button.
[Link] = "Click Here";

Similarly if you want to load an Image to a Button control , you can code like this
[Link] = [Link]("C:\\[Link]");
How to Call a Button's Click Event Programmatically

The Click event is raised when the Button control is clicked. This event is commonly used when no command
name is associated with the Button control. Raising an event invokes the event handler through a delegate.
private void Form1_Load(object sender, EventArgs e)
{
Button b = new Button();
[Link] += new EventHandler(ShowMessage);
[Link](b);
}
private void ShowMessage(object sender, EventArgs e)
{
[Link]("Button Click");
}

The following C# source code shows how to change the button Text property while Form loading event and to
display a message box when pressing a Button Control.

using System;
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
[Link] = "Click Here";
}

private void button1_Click(object sender, EventArgs e)


{
[Link]("[Link]
} } }

C# TextBox Control

A TextBox control is used to display, or accept as input, a single line of text.


This control has additional functionality that is not found in the standard
Windows text box control, including multiline editing and password character
masking.

A text box object is used to display text on a form or to get user input while a C# program is running. In a text
box, a user can type data or paste it into the control from the clipboard.

For displaying a text in a TextBox control , you can code like this

[Link] = "[Link]
You can also collect the input value from a TextBox control to a variable like this way

string var;
var = [Link];

C# TextBox Properties

You can set TextBox properties through Property window or through program. You can open Properties
window by pressing F4 or right click on a control and select Properties menu item

The below code set a textbox width as 250 and height as 50 through source code.
[Link] = 250;
[Link] = 50;
Background Color and Foreground Color

You can set background color and foreground color through property window and programmatically.

[Link] = [Link];
[Link] = [Link];

Textbox BorderStyle

You can set 3 different types of border style for textbox, they are None, FixedSingle and fixed3d.

[Link] = BorderStyle.Fixed3D;

TextBox Events

Keydown event

You can capture which key is pressed by the user using KeyDown event

e.g.

TextChanged Event
When user input or setting the Text property to a new value raises the TextChanged event

e.g.

Textbox Maximum Length

Sets the maximum number of characters or words the user can input into the text box control.

[Link] = 40;

Textbox ReadOnly

When a program wants to prevent a user from changing the text that appears in a text box, the program can set
the controls Read-only property is to True.

[Link] = true;

Multiline TextBox

You can use the Multiline and ScrollBars properties to enable multiple lines of text to be displayed or entered.

[Link] = true;

Textbox passowrd character

TextBox controls can also be used to accept passwords and other sensitive information. You can use the
PasswordChar property to mask characters entered in a single line version of the control

[Link] = '*';

The above code set the PasswordChar to * , so when the user enter password then it display only * instead of
typed characters.

How to Newline in a TextBox

You can add new line in a textbox using many ways.

[Link] += "your text" + "\r\n";

or

[Link] += "your text" + [Link];

How to retrieve integer values from textbox ?

int i;
i = [Link] ([Link]);
Parse method Converts the string representation of a number to its integer equivalent.

String to Float conversion

float i;
i = [Link] ([Link]);

String to Double conversion

double i;
i = [Link] ([Link]);
How to allow only numbers in a textbox

Many of us have faced a situation where we want the user to enter a number in a TextBox. Click the following
link that are going to make a Numeric Textbox which will accept only numeric values; if there are any values
except numeric. More about.... How do I make a textbox that only accepts numbers

Autocomplete TextBox

From the version Visual Studio 2005, some of the controls support Autocomplete
feature including the TextBox controls. The properties like
AutoCompleteCustomSource, AutoCompleteMode and AutoCompleteSource to
perform a TextBox that automatically completes user input strings by comparing the
prefix letters being entered to the prefixes of all strings in a data source. More
about.... C# Autocomplete TextBox

From the following C# source code you can see some important property settings to a
TextBox control.

Next : C# ComboBox

Download Source Code

Print Source Code

using System;
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
[Link] = 250;
[Link] = 50;
[Link] = true;
[Link] = [Link];
[Link] = [Link];
[Link] = BorderStyle.Fixed3D;
}

private void button1_Click(object sender, EventArgs e)


{
string var;
var = [Link];
[Link](var);
}
}
}

C# RadioButton Control

A radio button or option button enables the user to select a single option from a group of choices when paired
with other RadioButton controls. When a user clicks on a radio button, it becomes checked, and all other radio
buttons with same group become unchecked

The RadioButton control can display text, an Image, or both. Use the Checked property to get or set the state of
a RadioButton.

[Link] = true;
The radio button and the check box are used for different functions. Use a radio button when you want the user
to choose only one option. When you want the user to choose all appropriate options, use a check box. Like
check boxes, radio buttons support a Checked property that indicates whether the radio button is selected.

Next : C# CheckBox Control

Download Source Code


Print Source Code

using System;
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
[Link] = true;
}

private void button1_Click(object sender, EventArgs e)


{
if ([Link] == true)
{
[Link] ("You are selected Red !! ");
return;
}
else if ([Link] == true)
{
[Link]("You are selected Blue !! ");
return;
}
else
{
[Link]("You are selected Green !! ");
return;
}
}
}
}

C# ComboBox Control
C# controls are located in the Toolbox of the development environment, and you use them to create objects on
a form with a simple series of mouse clicks and dragging motions. A ComboBox displays a text box combined
with a ListBox, which enables the user to select items from the list or enter a new value .

The user can type a value in the text field or click the button to display a drop down list. You can add
individual objects with the Add method. You can delete items with the Remove method or clear the entire list
with the Clear method.

How add a item to combobox

[Link]("Sunday");
[Link]("Monday");
[Link]("Tuesday");
ComboBox SelectedItem

How to retrieve value from ComboBox

If you want to retrieve the displayed item to a string variable , you can code like this

string var;
var = [Link];
Or
var item = [Link]([Link]);
[Link](item);

How to remove an item from ComboBox

You can remove items from a combobox in two ways. You can remove item at a the specified index or giving
a specified item by name.

[Link](1);
The above code will remove the second item from the combobox.

[Link]("Friday");

The above code will remove the item "Friday" from the combobox.

DropDownStyle

The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a
drop-down. The DropDownStyle property also specifies whether the text portion can be edited.

[Link] = [Link];
ComboBox Selected Value

How to set the selected item in a comboBox

You can display selected item in a combobox in two ways.

[Link]("test1");
[Link]("test2");
[Link]("test3");
[Link] = "test3";
or
[Link] = [Link]("test3");
ComboBox DataSource Property

How to populate a combo box with a DataSet ?

You can Programmatically Binding DataSource to ComboBox in a simple way..

Consider an sql string like...."select au_id,au_lname from authors";

Make a datasource and bind it like the following...

[Link] = [Link][0];
[Link] = "au_id";
[Link] = "au_lname";
Combobox SelectedIndexChanged event

The SelectedIndexChanged event of a combobox fire when you change the slected item in a combobox. If you
want to do something when you change the selection, you can write the program on SelectedIndexChanged
event. From the following code you can understand how to set values in the SelectedIndexChanged event of a
combobox. Drag and drop two combobox on the Form and copy and paste the following source code.

using System;
using [Link];
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
[Link]("weekdays");
[Link]("year");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
[Link]();
if ([Link] == "weekdays")
{
[Link]("Sunday");
[Link]("Monday");
[Link]("Tuesday");
}
else if ([Link] == "year")
{
[Link]("2012");
[Link]("2013");
[Link]("2014");
}
}
}
}

Output
ComboBox Databinding

You can bind data to a Combobox from various resources like Dataset, List, Enum, Dictionary etc. From the
following link you can study more about ... ComboBox Databinding

ComboBox Default Value

How to set a default value for a Combo Box

You can set combobox default value by using SelectedIndex property

[Link] = 6;

Above code set 6th item as combobox default value

ComboBox readonly

How to make a combobox read only

You can make a ComboBox readonly, that means a user cannot write in a combo box but he can select the
given items, in two ways. By default, DropDownStyle property of a Combobox is DropDown. In this case user
can enter values to combobox. When you change the DropDownStyle property to DropDownList, the
Combobox will become read only and user can not enter values to combobox. Second method, if you want the
combobox completely read only, you can set [Link] = false.

Autocomplete ComboBox

From the version Visual Studio 2005, some of the controls support Autocomplete feature including the
ComboBox controls. From the following link you can see how to make .... Autocomplete ComboBox

ComboBox Example

The following C# source code add seven days in a week to a combo box while load event of a Windows Form
and int Button click event it displays the selected text in the Combo Box.

Next : C# ListBox Control

Download Source Code

Print Source Code

using System;
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
[Link]("Sunday");
[Link]("Monday");
[Link]("Tuesday");
[Link]("wednesday");
[Link]("Thursday");
[Link]("Friday");
[Link]("Saturday");
[Link] = [Link]("Sunday");

private void button1_Click(object sender, EventArgs e)


{
string var;
var = [Link];
[Link](var);
}
}
}

C# ListBox Control

The ListBox control enables you to display a list of items to the user that the user can select by clicking.
In addition to display and selection functionality, the ListBox also provides features that enable you to
efficiently add items to the ListBox and to find text within the items of the list. You can use the Add or Insert
method to add items to a list box. The Add method adds new items at the end of an unsorted list box.

[Link]("Sunday");

If you want to retrieve a single selected item to a variable , you can code like this

string var;
var = [Link];

The SelectionMode property determines how many items in the list can be selected at a time. A ListBox
control can provide single or multiple selections using the SelectionMode property . If you change the selection
mode property to multiple select , then you will retrieve a collection of items from [Link]
property.

[Link] = [Link];

The following C# program initially fill seven days in a week while in the form load event and set the selection
mode property to MultiSimple. At the Button click event it will display the selected items.

using System;
using [Link];
using [Link];
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
[Link]("Sunday");
[Link]("Monday");
[Link]("Tuesday");
[Link]("Wednesday");
[Link]("Thursday");
[Link]("Friday");
[Link]("Saturday");
[Link] = [Link];
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Object obj in [Link] )
{
[Link]([Link] ());
}
}
}
}
How to bind a ListBox to a List ?

First you should create a fresh List Object and add items to the List.

List<string> nList = new List<string>();


[Link]("January");
[Link]("February");
[Link]("March");
[Link]("April");

The next step is to bind this List to the Listbox. In order to do that you should set datasource of the Listbox.

[Link] = nList;

Full Source code

private void button1_Click(object sender, EventArgs e)


{
List<string> nList = new List<string>();
[Link]("January");
[Link]("February");
[Link]("March");
[Link]("April");
[Link] = nList;
}

How to bind a listbox to database values ?

First you should create a connection string and fetch data from database to a Dataset.

connetionString = "Data Source=ServerName;Initial Catalog=databasename;User


ID=userid;Password=yourpassword";
sql = "select au_id,au_lname from authors";

After that you should set Listbox datasoure as Dataset.

[Link] = [Link][0];
[Link] = "au_id";
[Link] = "au_lname";

using System;
using [Link];
using [Link];
using [Link];
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
//connetionString = "Data Source=ServerName;Initial Catalog=databasename;User
ID=userid;Password=yourpassword";
//sql = "select au_id,au_lname from authors";
connection = new SqlConnection(connetionString);
try
{
[Link]();
command = new SqlCommand(sql, connection);
[Link] = command;
[Link](ds);
[Link]();
[Link]();
[Link]();
[Link] = [Link][0];
[Link] = "au_id";
[Link] = "au_lname";
}
catch (Exception ex)
{
[Link]("Cannot open connection ! ");
}
}
}
}

How to refresh DataSource of a ListBox ?

How to clear the Listbox if its already binded with datasource ?

When you want to clear the Listbox, if the ListBox already binded with Datasource, you have to set the
Datasource of Listbox as null.

[Link] = null;

How to SelectedIndexChanged event in ListBox ?

This event is fired when the item selection is changed in a ListBox. You can use this event in a situation that
you want select an item from your listbox and accodring to this selection you can perform other programming
needs.

You can add the event handler using the Properties Window and selecting the Event icon and double-clicking
on SelectedIndexChanged as you can see in following image.

The event will fire again when you select a new item. You can write your code within SelectedIndexChanged
event . When you double click on ListBox the code will automatically come in you code editor like the
following image.

From the following example you can understand how to fire the SelectedIndexChanged event
First you should drag two listboxes on your Form. First listbox you should set the List as Datasource, the List
contents follows:

List<string> nList = new List<string>();


[Link]("First Quarter");
[Link]("Second Quarter");

When you load this form you can see the listbox is populated with List and displayed first quarter and second
quarter. When you click the "Fist Quarter" the next listbox is populated with first quarter months and when you
click "Second Quarter" you can see the second listbox is changed to second quarter months. From the
following program you can understand how this happened.

Next : C# Checked ListBox Control

Download Source Code


Print Source Code

using System;
using [Link];
using [Link];
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

List < string > fQ = new List < string > ();
List < string > sQ = new List < string > ();

private void Form1_Load(object sender, EventArgs e)


{
[Link]("January");
[Link]("February");
[Link]("March");

[Link]("April");
[Link]("May");
[Link]("June");

List < string > nList = new List < string > ();

[Link]("First Quarter");
[Link]("Second Quarter");

[Link] = nList;
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
if ([Link] == 0)
{
[Link] = null;
[Link] = fQ;
}
else if ([Link] == 1)
{
[Link] = null;
[Link] = sQ;
}
}

}
}

C# Menu Control

A Menu on a Windows Form is created with a MainMenu object, which is a collection of MenuItem objects.
MainMenu is the container for the Menu structure of the form and menus are made of MenuItem objects that
represent individual parts of a menu.

You can add menus to Windows Forms at design time by adding the MainMenu component and then
appending menu items to it using the Menu Designer.
After drag the Menustrip on your form you can directly create the menu items by type a value into the "Type
Here" box on the menubar part of your form. From the following picture you can understand how to create
each menu items on mainmenu Object.

If you need a seperator bar , right click on your menu then go to insert->Seperator.
After creating the Menu on the form , you have to double click on each menu item and write the programs
there depends on your requirements. The following C# program shows how to show a messagebox when
clicking a Menu item.

Next : C# MDI Form

Download Source Code


Print Source Code

using System;
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)


{
[Link]("You are selected MenuItem_1");
}
}
}

C# Font Dialog Box

Font dialog box represents a common dialog box that displays a list of fonts that are currently installed on the
system. The Font dialog box lets the user choose attributes for a logical font, such as font family and associated
font style, point size, effects , and a script .

The following C# program invites a Font Dialog Box and retrieve the selected Font Name and Font Size.

Next : C# OpenFile Dialog Box

Download Source Code


Print Source Code

using System;
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FontDialog dlg = new FontDialog();
[Link]();

if ([Link]() == [Link])
{
string fontName;
float fontSize;
fontName = [Link];
fontSize = [Link];
[Link](fontName + " " + fontSize );
}
}
}
}

C# Timer Control

What is Timer Control ?

The Timer Control plays an important role in the development of programs both Client side and Server side
development as well as in Windows Services. With the Timer Control we can raise events at a specific
interval of time without the interaction of another thread.

Use of Timer Control

We require Timer Object in many situations on our development environment. We have to use Timer Object
when we want to set an interval between events, periodic checking, to start a process at a fixed time schedule,
to increase or decrease the speed in an animation graphics with time schedule etc.

A Timer control does not have a visual representation and works as a component in the background.

How to Timer Control ?

We can control programs with Timer Control in millisecond, seconds, minutes and even in hours. The Timer
Control allows us to set Intervel property in milliseconds. That is, one second is equal to 1000 milliseconds.
For example, if we want to set an interval of 1 minute we set the value at Interval property as 60000, means
60x1000 .
By default the Enabled property of Timer Control is False. So before running the program we have to set the
Enabled property is True , then only the Timer Control starts its function.

Timer example

In the following program we display the current time in a Label Control. In order to develop this program, we
need a Timer Control and a Label Control. Here we set the timer interval as 1000 milliseconds, that means one
second, for displaying current system time in Label control for the interval of one second.

using System;
using [Link];
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
[Link] = [Link]();
}
}
}

Start and Stop Timer Control

The Timer control have included the Start and Stop methods for start and stop the Timer control functions.

Here we run this program only 10 seconds. In order to doing this ,in the following program we set Timer
interval as 1000 (1 second) and check each seconds for stopping the Timer Control after 10 seconds.

Next : C# Visual Studio IDE


Download Source Code
Print Source Code

using System;
using [Link];

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
int second = 0;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
[Link] = 1000;
[Link]();
}

private void timer1_Tick(object sender, EventArgs e)


{
[Link] = [Link]();
second = second + 1;
if (second >= 10)
{
[Link]();
[Link]("Exiting from Timer....");
}
}
}
}

C# OpenFile Dialog Box

The OpenFileDialog component allows users to browse the folders of their computer or any computer on the
network and select one or more files to open. The dialog box returns the path and name of the file the user
selected in the dialog box.
The FileName property can be set prior to showing the dialog box. This causes the dialog box to initially
display the given filename. In most cases, your applications should set the InitialDirectory, Filter, and
FilterIndex properties prior to calling ShowDialog.

The following C# program invites an OpenFile Dialog Box and retrieve the selected filename to a string.

Next : C# Print Dialog Box

Download Source Code


Print Source Code

using System;
using [Link];
using [Link];

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
OpenFileDialog dlg = new OpenFileDialog();
[Link]();

if ([Link]() == [Link])
{
string fileName;
fileName = [Link];
[Link](fileName);
}
}
}
}

You might also like