Event Driven Programming in C# Windows Form Application
Event Driven Programming in C# Windows Form Application
programming in C#
Windows Form
Application [1]
C# Hello World
A Windows forms application is one that runs on the desktop computer. A Windows forms
application will normally have a collection of controls such as labels, textboxes, buttons,
radiobuttonbox, checkbox, etc.
Now let's look at an example of how we can implement a simple 'hello world' application in Visual
Studio. For this, we would need to implement the below-mentioned steps
Step 1) The first step involves the creation of a new project in Visual Studio. After launching
Visual Studio, you need to choose the menu option New->Project.
Step 2) The next step is to choose the project type as a Windows Forms application. Here we also
need to mention the name and location of our project.
1|Page
Compiled by Milkesa A. for Information Systems Year II Students
1. In the project dialog box, we can see various options for creating different types of projects
in Visual Studio. Click the Windows option on the left-hand side.
2. When we click the Windows options in the previous step, we will be able to see an option
for Windows Forms Application. Click this option.
3. We will give a name for the application. In our case, it is DemoApplication. We will also
provide a location to store our application.
4. Finally, we click the 'OK' button to let Visual Studio create our project.
If the above steps are followed, you will get the below output in Visual Studio.
Output: -
2|Page
Compiled by Milkesa A. for Information Systems Year II Students
You will see a Form Designer displayed in Visual Studio. It's in this Form Designer that you will
start building your Windows Forms application.
In the Solution Explorer, you will also be able to see the DemoApplication Solution. This solution
will contain the below 2 project files
1. A Form application called Forms1.cs. This file will contain all of the code for the Windows
Form application.
2. The Main program called Program.cs is default code file which is created when a new
application is created in Visual Studio. This code will contain the startup code for the
application as a whole.
Below is an example of a simple Windows form application C#. It shows a simple Login screen,
which is accessible by the user. The user will enter the required credentials and then will click the
Login button to proceed.
3|Page
Compiled by Milkesa A. for Information Systems Year II Students
1. This is a collection of label controls which are normally used to describe adjacent controls
(textbox). So, in our case, we have 2 textboxes, and the labels are used to tell the user that
one textbox is for entering the user’s name and the other for the password.
2. The 2 textboxes are used to hold the username and password which will be entered by the
user.
3. Finally, we have the button control. The button control will normally have some code
attached to perform a certain set of actions. So, for example in the above case, we could
have the button perform an action of validating the user’s name and password which is
entered by the user.
In order to understand how these controls, do their function, the basic thing we have to know
is about properties and events of those controls.
Property is the behavior that one control has whereas event is the action that is performed by
the controls when we click, move mouse over the control, etc.
4|Page
Compiled by Milkesa A. for Information Systems Year II Students
To see the property of the above textbox full name, right click on the textbox and click on the
properties button then you will see the properties of that control (textbox). Look at the
following
Name: is the property which all controls have. It used to call and use this controls in the
program; like human being called by his/her name, every control called by their own name.
Backcolor: is property that is used to set back ground color of that controls.
5|Page
Compiled by Milkesa A. for Information Systems Year II Students
The above are some properties of the textbox and other controls. But properties of controls
are not limited only to the above; there are also other properties and check it by your own.
6|Page
Compiled by Milkesa A. for Information Systems Year II Students
The above are events that textbox and other controls can have. Some main events of textbox are:
Leave: this event that used to take some action if we leave that control (textbox).
For example, if we double click on that event we will see the following:
7|Page
Compiled by Milkesa A. for Information Systems Year II Students
Validating: is another event of Textbox and it is here where we write the code to validate the value
that Textbox must retrieve. We can write in leave event also.
TextChanged: is event that perform action if the text of that controls changed.
(object sender, EventArgs e) is parameter for the Leave event and sender is the object sender that
raised the event whereas EventArgs represents the data related to that event and e is instance of
EventArgs
To see the Properties and Events of other controls you can follow the same step we have discussed
on the TextBox.
8|Page
Compiled by Milkesa A. for Information Systems Year II Students
Note! The default event of Button is Click and check the default event of other controls double
click on the control and see it.
for instance, the above login Form has TextBox, Label and Button controls. The two TextBox used
to take username and password from the user respectively. And the label near the TextBoxs is used
has indicator. the Button ‘login’ perform login function when user click on it. Therefore, whenever
we want to use one control to perform one function, we have to write that Function’s algorithm
(program) under one of the events of that control. And, we choose the event in which we have to
write that program based on the goal of that function.
For Example, the aim of the above login Button is to validate user input and takes the user to the
system when it is clicked by the user, so that, we have to write the program that checks
authentication of the user and enables the user to enter to the system if that user is authenticated.
we have to write the program that authenticate user and takes authenticated user to the system.
In C# programming as you know the default user input is text (string) type.
Look at the following form, its aim is to display the name of the user entered to the TextBox on
Label ‘Show Result’.
9|Page
Compiled by Milkesa A. for Information Systems Year II Students
Double click on the button show and Write lblshow.Text = txtname.Text; between the two
braces
10 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Each control called by its name when we want to use it in the program
As you know to use number digits in the C# windows form program, we have cast from string to
other data types like, double, int, float, etc.
11 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
The above calculator receives two numbers from the user and perform needed arithmetic operation
and show the result on the ‘Result’ Label
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace seccalculator
{
public partial class frmcalculator : Form
{
public frmcalculator()
{
InitializeComponent();
}
12 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
13 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
double b = double.Parse(txtsecondnum.Text);
if (b == 0) //this condition is to check whether the second number is zero or not
{
MessageBox.Show("number cannot be divided by zero"); //used to display the 'number
cannot be divided by zero' if the condition is true
txtsecondnum.Clear();
txtsecondnum.Focus();
}
else
{
lblresult.Text = (double.Parse(txtfirstnum.Text) /
double.Parse(txtsecondnum.Text)).ToString();
//devide the first number by the second one if it is not zero
}
}
14 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
We had already seen how to add a control to a form when we added the label, textbox and button
control in the earlier section to display "your name."
Let's look at the other controls available for Windows forms and see some of their common
properties.
Group Box
A group box is used for logical grouping controls into a section. Let's take an example if you had
a collection of controls for entering details such as name and address of a person. Ideally, these
are details of a person, so you would want to have these details in a separate section on the Form.
For this purpose, you can have a group box. Let's see how we can implement this with an example
shown below
Step 1) The first step is to drag the Groupbox control onto the Windows Form from the toolbox as
shown below
15 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Step 2) Once the groupbox has been added, go to the properties window by clicking on the
groupbox control. In the properties window, go to the Text property and change. For example
change it to "User Details".
Once you make the above changes, you will see the following output
In the output, you can clearly see that the Groupbox was added to the form. You can also see that
the text of the groupbox was changed to "User Details."
So, now when can add controls we want to group in the this groupbox section. For instance, let us
the above controls we have discussed (label, textbox).
16 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Now you can see label and textbox are added in the groupbox ‘User Detail’)
17 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
List box
A Listbox is used to showcase a list of items on the Windows form. Let's see how we can
implement this with an example shown below. We will add a list box to the form to store some
city locations.
Step 1) The first step is to drag the list box control onto the Windows Form from the toolbox as
shown below
Step 2) Once the list box has been added, go to the properties window by clicking on the list box
control.
18 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
1. First, change the property of the Listbox box control, in our case, we have changed this to
lstCity
2. Click on the Items property. This will allow you to add different items which can show up
in the list box. In our case, we have selected items "collection".
3. In the String Collection Editor, which pops up, enter the city names. In our case, we have
entered "Mumbai", "Bangalore" and "Hyderabad".
4. Finally, click on the 'OK' button.
Once you make the above changes, you will see the following output
In the output, you can see that the Listbox was added to the form. You can also see that the list
box has been populated with the city values.
RadioButton
A Radiobutton is used to showcase a list of items out of which the user can choose one. Let's see
how we can implement this with an example shown below. We will add a radio button for a
male/female option.
19 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Step 1) The first step is to drag the 'radiobutton' control onto the Windows Form from the toolbox
as shown below.
step 2) Once the Radiobutton has been added, go to the properties window by clicking on the
Radiobutton control.
First, you need to change the text property of both Radio controls. Go the properties windows and
change the text to a male of one radiobutton and the text of the other to female.
Similarly, change the name property of both Radio controls. Go the properties windows and
change the name to 'rdMale' of one radiobutton and to 'rdfemale' for the other one.
20 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
One you make the above changes, you will see the following output
Checkbox
A checkbox is used to provide a list of options in which the user can choose multiple choices. Let's
see how we can implement this with an example shown below. We will add 2 checkboxes to our
Windows forms. These checkboxes will provide an option to the user on whether they want to
learn C# or ASP.Net.
Step 1) The first step is to drag the checkbox control onto the Windows Form from the toolbox as
shown below
21 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Step 2) Once the checkbox has been added, go to the properties window by clicking on the
Checkbox control.
First, you need to change the text property of both checkbox controls. Go the properties windows
and change the text to C# and ASP.Net.
Similarly, change the name property of both Radio controls. Go the properties windows and
change the name to chkC of one checkbox and to chkASP for the other one.
Once you make the above changes, you will see the following output
22 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
ComboBox C#
C# ComboBox is a combination of a TextBox and a ListBox control. Only one list item is
displayed at one time in a ComboBox and other available items are loaded in a drop down list.
Accessing Data from a database is one of the important aspects of any programming language. It
is an absolute necessity for any programming language to have the ability to work with databases.
C# is no different.
It can work with different types of databases. It can work with the most common databases such
as Oracle and Microsoft SQL Server.
It also can work with new forms of databases such as MongoDB and MySQL.
23 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
✓ Updating Records
✓ Deleting Records
✓ Connecting Controls to Data
✓ C# DataGridView
In working with databases, the following are the concepts which are common to all databases.
1. Connection – To work with the data in a database, the first obvious step is the connection. The
connection to a database normally consists of the below-mentioned parameters.
✓ Server Name or Data Source – The first important parameter is the server’s name to
which the connection needs to be established. Each connection can only work with one
server at a time.
➢ We can use dot (‘.’) instead of server name. And the difference between using specific
server name and using dot (.) is:
• if we develop a given program on one machine and later import into another
machine it does not work if we do not change the server’s name to the new
machine’s name.
• but if we use dot (.) it will work with another server name; because, (.)
represents every server
✓ Initial Catalog- this is the second parameter in connecting to the server and it is database
name to which our program is going to be connected. each connection can only work with
one database at a time.
✓ Credentials – The next important aspect is the username and password which needs to be
used to establish a connection to the database. It ensures that the username and password
have the necessary privileges to connect to the database if we want to use sql server
authentication. But we can set Integrated Security=True if we want to use windows
authentication.
24 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
✓ Optional parameters - For each database type, you can specify optional parameters to
provide more information on how .net should handle the connection to the database. For
example, one can specify a parameter for how long the connection should stay active. If no
operation is performed for a specific period of time, then the parameter would determine if
the connection has to be closed.
Some other built in classes that are used to work on the data in the database are the following:
SqlCommand- allow the user to query and send the commands to the database. SQL command
is specified by the SQL connection object. Two methods are used, ExecuteReader method for
results of query and ExecuteNonQuery for insert, Update, and delete commands. It is the
method that is best for the different commands. The parameters of this class is:
✓ sql query
✓ connection string object.
25 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
db.opencon() is the connection string and the lines before it is the query that inserts data into the
database.
SqlDataAdapter-it can be used to write to and read from the database and it is the fastest to
read from it.
Example:
Selecting data from the database – Once the connection has been established, the next
important aspect is to fetch the data from the database. C# can execute 'SQL' select command
against the database. The 'SQL' statement can be used to fetch data from a specific table in the
database. Look the following program that select data from the database
26 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
}
else
{
MessageBox.Show("invalid user name or password",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
//the above MessageBox.Show() metthod used to show the
message to the user if the condition is not satisfied
}
27 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Inserting data into the database – C# can also be used to insert records into the database.
Values can be specified in C# for each row that needs to be inserted into the database.
The following creating account program is one example of inserting data into database
28 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
,[gender]
,[DOB])
VALUES
('" + txtid.Text + "','" + txtFname.Text + "','" +
txtUname.Text + "','" + txtPassword.Text + "','" + txtEmail.Text + "','"
+ TxtPhone.Text + "','" + cmbGender.Text + "','" + dtpDoB.Value + "')",
db.opencon()); //inserts data from the controls to the table called
registration found labsession database
29 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Updating data into the database – C# can also be used to update existing records into the
database. New values can be specified in C# for each row that needs to be updated into the
database. Look at the following example
30 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Deleting data from a database – C# can also be used to delete records into the database.
Select commands to specify which rows need to be deleted can be specified in C#. example
31 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
C# DataGridView
Data Grids are used to display data from a table in a grid-like format. When a user sees's table
data, they normally prefer seeing all the table rows in one shot. This can be achieved if we can
display the data in a grid on the form.
C# and Visual Studio have inbuilt data grids, this can be used to display data. Let's take a look at
an example of this. In our example, we will have a data grid, which will be used to display the
employee id, employee name, phone number, date of birth, gender and email from the database
called ‘registrattion’
32 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
using System;
using System.Collections.Generic;
using System.ComponentModel;
33 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SecondLabPractice
{
public partial class userDetail : Form
{
Dbconnection cn = new Dbconnection();
SqlDataAdapter sda;
SqlCommand cmd;
DataTable dt;
public userDetail()
{
InitializeComponent();
}
34 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
35 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
DGVuserdetail.Rows[r].Cells[1].Value =
i["empname"].ToString();
DGVuserdetail.Rows[r].Cells[2].Value =
i["phonenum"].ToString();
DGVuserdetail.Rows[r].Cells[3].Value =
i["empDOB"].ToString();
DGVuserdetail.Rows[r].Cells[4].Value =
i["gender"].ToString();
DGVuserdetail.Rows[r].Cells[5].Value =
i["email"].ToString();
}
}
}
else
{
foreach(DataRow dr in dt.Rows)
{
int nl = DGVuserdetail.Rows.Add();
DGVuserdetail.Rows[nl].Cells[0].Value =
dr["userId"].ToString();
DGVuserdetail.Rows[nl].Cells[1].Value =
dr["Fname"].ToString();
DGVuserdetail.Rows[nl].Cells[2].Value =
dr["phone"].ToString();
DGVuserdetail.Rows[nl].Cells[3].Value =
dr["DOB"].ToString();
DGVuserdetail.Rows[nl].Cells[4].Value =
dr["gender"].ToString();
DGVuserdetail.Rows[nl].Cells[5].Value =
dr["email"].ToString();
}
}
{
btnSearch.Enabled = true;
}
}
38 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
39 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
}
}
}
40 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
3. Double click on one row and you will see records in the textboxs
41 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
42 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
43 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students
Reference
44 | P a g e