You are on page 1of 45

Event Driven

programming in C#
Windows Form
Application [1]

Compiled by Milkesa A. for Information Systems Year II Students


Compiled by Milkesa A. for Information Systems Year II Students

Windows Forms Basics

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

So, an example of the controls available in the above application

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.

Therefore, now let us see what is property and event of a control

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

How we can work with property and events of controls?

For example, let us see the following form

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

Some main properties of textbox are 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.

Text: is the property that is aimed to display the something in textbox

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

Forecolor: is used to set color of texts in that control.

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.

Now let us see some events of textbox

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

From the above image:

textBox1- is the name of the text box

Leave-is event of textBox1

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.

private void txtphone_Validating(object sender, CancelEventArgs e)


{
Here we can write the code that validates the values user enters to TextBox txtphone

TextChanged: is event that perform action if the text of that controls changed.

It is the default event TextBox control.

private void txtphone_TextChanged(object sender, EventArgs e)


{

(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.

Now let us see how to develop a given program using controls

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.

private void btnlogin_Click(object sender, EventArgs e)

we have to write the program that authenticate user and takes authenticated user to the system.

How to handle and work on the user input?

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

The program that accomplishes the above needed function is as follows

Double click on the button show and Write lblshow.Text = txtname.Text; between the two

braces

private void btnshow_Click(object sender, EventArgs e)

lblshow.Text = txtname.Text; // to show the value of the Textbox in the label

Let us run and see

10 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

lblshow: is the name of the label

txtname: is the name of the TextBox

what you can understand from this?

Each control called by its name when we want to use it in the program

How to handle and work on number digits?

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.

To understand simply, let us develop simple calculator that do arithmetic operation

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

The program that performs the needed function is the following

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

private void btnadd_Click(object sender, EventArgs e)


{
lblresult.Text = (double.Parse(txtfirstnum.Text) +
double.Parse(txtsecondnum.Text)).ToString();
//adding the two numbers. Parse() bult in function which is used to convert one data type to
other data type. For instance in the above statement (double.Parse(txtfirstnum.Text) used to
convert string type to double. After completing the addition operation ToString() convert the
result to string and assign that result to lblresult.Text to display the result on it.
}

private void btnsub_Click(object sender, EventArgs e)


{
lblresult.Text = (double.Parse(txtfirstnum.Text) -
double.Parse(txtsecondnum.Text)).ToString();
//substracting the two numbers
}

private void btnmult_Click(object sender, EventArgs e)


{
lblresult.Text = (double.Parse(txtfirstnum.Text) *
double.Parse(txtsecondnum.Text)).ToString();
//to get the product of the two numbers
}

private void btndiv_Click(object sender, EventArgs e)


{

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
}
}

private void btnclear_Click(object sender, EventArgs e)


{
tclear();//method calling
}
public void tclear() //is the method to clear the controls
{
txtfirstnum.Clear();
txtsecondnum.Text = "";
lblresult.Text = "";
}
}
}

14 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

Adding more Controls to a form

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

First add label

Then, Add textbox

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.

C# Database Connection: How to connect SQL Server (Example)

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.

In this C# sql connection tutorial, you will learn-

✓ Fundamentals of database connectivity


✓ How to connect C# to database
✓ Access data with the SqlDataAdapter
✓ C# Insert into Database

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

The first important thing in connecting C# to Database is including ‘using


System.Data.SqlClient;’ Namespace. Because, ‘SqlConnection’ class is found in this space;
unless we add this namespace to our program, we cannot connect our C# program to local server.

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.

Look at the following example of connection string.

SqlConnection sq= new SqlConnection("Data Source=.;Initial Catalog=labsession;Integrated


Security=True"); // this is the string that connects C# to server.

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.

Example: cmd = new SqlCommand(@"INSERT INTO [dbo].[register]


([userId]
,[Fname]
,[userName]
,[password]
,[email]
,[phone]
,[gender]
,[DOB])
VALUES

25 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

('" + txtid.Text + "','" + txtFname.Text + "','"


+ txtUname.Text + "','" + txtPassword.Text + "','" +
txtEmail.Text + "','" + TxtPhone.Text + "','" + cmbGender.Text
+ "','" + dtpDoB.Value + "')", db.opencon());

db.opencon() is the connection string and the lines before it is the query that inserts data into the
database.

What is the use of @ symbol before the above query?

It used to support multiple line string values

SqlDataAdapter-it can be used to write to and read from the database and it is the fastest to
read from it.

Example:

SqlDataAdapter sd = new SqlDataAdapter("SELECT * fROM [dbo].[register] WHERE


userName='" + txtUname.Text + "' ", db.opencon());

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

The namespace for DataTable class is ‘using System.Data;’

It is the program written for login purpose

private void btnlogin_Click(object sender, EventArgs e)


{
sqlcon = new SqlConnection("Data Source=.;Initial
Catalog=labsession;Integrated Security=True");//coonnecting to the
server

26 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

sda = new SqlDataAdapter(@"SELECT * FROM[dbo].[login] WHERE


password='"+txtpassword.Text+ "' and username='" + txtuser.Text + "'",
sqlcon);//reading from the database
dt = new DataTable();//this to create the instance of
DataTable Class
sda.Fill(dt);//Fiil() method is used to fill the DataTable
with the data retrieved from the database
if (dt.Rows.Count == 1)//condition to check wether the
needed data is exist or not
{
frmmain fr = new frmmain("wel come"+" "+txtuser.Text);
//the code executed if thhe condition is true
fr.Show();
this.Hide();

}
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
}

Design of the above program look like the following

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

private void btnregister_Click(object sender, EventArgs e)


{

sd = new SqlDataAdapter("SELECT * fROM [dbo].[register]


WHERE userName='" + txtUname.Text + "' ", db.opencon());
DataTable dt = new DataTable();
sd.Fill(dt);
db.conclose();
if (dt.Rows.Count == 0)
{
cmd = new SqlCommand(@"INSERT INTO [dbo].[register]
([userId]
,[Fname]
,[userName]
,[password]
,[email]
,[phone]

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

cmd.ExecuteNonQuery();//ExecuteNonQuery is method used


for executing queries that does not return. ExecuteNonQuery executes the
command and returns the number of rows affected.
db.conclose();//close the connection
MessageBox.Show("registered");
}
else
{
MessageBox.Show("user name found");
txtUname.Focus();
}

29 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

Form design of the above inserting values program

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

private void btnUpdate_Click(object sender, EventArgs e)


{
DialogResult dl = new DialogResult();//create dialogbox for
user confirmation
dl= MessageBox.Show("Are sure to
update?","notificatio",MessageBoxButtons.YesNo);
if (dl == DialogResult.Yes)//condition to check whether user
click 'yes' button of dialogbox
{

30 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

cmd = new SqlCommand(@"UPDATE [dbo].[registrattion] SET


empid = '" + txtID.Text + "',empname ='" + txtName.Text + "',phonenum =
'" + txtPhone.Text + "',email = '" + txtuseremail.Text + "'WHERE empid='"
+ txtID.Text + "'", cn.opencon());//update records of 'registrattion'
table based on empid column.
cmd.ExecuteNonQuery();
cn.conclose();
MessageBox.Show("one user data is updated!");

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

private void btnDelete_Click(object sender, EventArgs e)


{
DialogResult dl = new DialogResult();
dl = MessageBox.Show("Are sure to update?", "warning",
MessageBoxButtons.YesNo);
if (dl == DialogResult.Yes)
{
cmd = new SqlCommand(@"DELETE FROM [dbo].[registrattion]
WHERE empid='" + txtID.Text + "' ", cn.opencon());//deletes record from
registrattion based on empid column values.
cmd.ExecuteNonQuery();
cn.conclose();

31 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

MessageBox.Show("the data with '" + txtID.Text + "' is


deleted");
}

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

From the above form ‘User Detail’:

✓ Button Update is used to update the records of the database


✓ Button Delete is used to delete records from the database.
✓ Button Search used to search a single record from the database
✓ Button All Detail used to display all the records in the table
✓ DataGridView is used to display the data that comes from the database and when its cells
content is double clicked by the user the records in that cells displayed in the textbox found
in the form.

Generally, the program that achieves the above description is as follows

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();
}

private void userDetail_Load(object sender, EventArgs e)


{
btnDelete.Enabled = btnSearch.Enabled = btnUpdate.Enabled =
false;
}

private void userDetail_FormClosed(object sender,


FormClosedEventArgs e)
{

34 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

private void userDetail_FormClosing(object sender,


FormClosingEventArgs e)
{
DialogResult dl = new DialogResult();
dl = MessageBox.Show("Sure to close", "warning",
MessageBoxButtons.OKCancel);
if (dl == DialogResult.OK)
{
Application.Exit();
}
else if (dl == DialogResult.Cancel)
{
e.Cancel = true;
}
}
public void detail()
{

sda = new SqlDataAdapter(@"SELECT *


FROM[dbo].[registrattion]", cn.opencon());
dt = new DataTable();
sda.Fill(dt);
cn.conclose();
foreach (DataRow i in dt.Rows)
{
int r = DGVuserdetail.Rows.Add();
DGVuserdetail.Rows[r].Cells[0].Value =
i["empid"].ToString();

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();
}
}

private void btnalldetail_Click(object sender, EventArgs e)


{
DGVuserdetail.Rows.Clear();
detail();
}

private void btnSearch_Click(object sender, EventArgs e)


{
DGVuserdetail.Rows.Clear();
sda = new SqlDataAdapter(@"SELECT * FROM[dbo].[
registrattion] WHERE empid='"+txtSearch.Text+"'", cn.opencon());
dt = new DataTable();
cn.conclose();
sda.Fill(dt);
if (dt.Rows.Count == 0)
{
MessageBox.Show("No user with '" + txtSearch.Text + "'
is found!");
36 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

}
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();
}
}

private void txtSearch_TextChanged(object sender, EventArgs e)


{
if (txtSearch.Text == "")
{
btnSearch.Enabled = false;
}
else
37 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

{
btnSearch.Enabled = true;
}
}

private void txtID_TextChanged(object sender, EventArgs e)


{
if (txtID.Text == "")
{
btnDelete.Enabled = btnUpdate.Enabled = false;
}
else
{
btnUpdate.Enabled = btnDelete.Enabled = true;

private void DGVuserdetail_MouseDoubleClick(object sender,


MouseEventArgs e)
{
txtID.Text =
DGVuserdetail.SelectedRows[0].Cells[0].Value.ToString();
txtName.Text =
DGVuserdetail.SelectedRows[0].Cells[1].Value.ToString();
txtPhone.Text =
DGVuserdetail.SelectedRows[0].Cells[2].Value.ToString();
txtuseremail.Text =
DGVuserdetail.SelectedRows[0].Cells[5].Value.ToString();

38 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

private void btnclearall_Click(object sender, EventArgs e)


{
txtuseremail.Clear();
txtID.Clear();
txtName.Clear();
txtPhone.Clear();

private void btnUpdate_Click(object sender, EventArgs e)


{
DialogResult dl = new DialogResult();//create dialogbox for
user confirmation
dl= MessageBox.Show("Are sure to
update?","notificatio",MessageBoxButtons.YesNo);
if (dl == DialogResult.Yes)//condition to check whether user
click 'yes' button of dialogbox
{
cmd = new SqlCommand(@"UPDATE [dbo].[registrattion] SET
empid = '" + txtID.Text + "',empname ='" + txtName.Text + "',phonenum =
'" + txtPhone.Text + "',email = '" + txtuseremail.Text + "'WHERE empid='"
+ txtID.Text + "'", cn.opencon());//update records of 'registrattion'
table based on empid column.
cmd.ExecuteNonQuery();
cn.conclose();
MessageBox.Show("one user data is updated!");

39 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

private void btnDelete_Click(object sender, EventArgs e)


{
DialogResult dl = new DialogResult();
dl = MessageBox.Show("Are sure to update?", "warning",
MessageBoxButtons.YesNo);
if (dl == DialogResult.Yes)
{
cmd = new SqlCommand(@"DELETE FROM [dbo].[registrattion]
WHERE empid='" + txtID.Text + "' ", cn.opencon());//deletes record from
registrattion based on empid column values.
cmd.ExecuteNonQuery();
cn.conclose();
MessageBox.Show("the data with '" + txtID.Text + "' is
deleted");
}

}
}
}

If you run the above program

1. The first form you will see

40 | P a g e
Compiled by Milkesa A. for Information Systems Year II Students

2. Click on ‘All Detail’ button you will the following

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

4. Search by the id that is found in the table

5. Search by id not found

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

[1] "guru99," [Online]. Available: https://www.guru99.com/c-sharp.

please do not forget to refer the above reference

44 | P a g e

You might also like