WordPress Websites for Engineers: Elevate Your Brand
Winforms
1. C# Windows Forms
Page 1 of 15
Windows Forms in C#
So far, we have seen console application development now we will see graphical
application development (desktop) in C#. To develop graphical user interface based
application .Net framework proved us a namespace System.Windows.Forms. In this
namespace there are many classes for each control. Some of them are listed below.
• Button Controls: The Button, CheckBox, and RadioButton controls are designed to
permit users to make one or more selections on a form.
• PictureBox and TextBoxt Controls: The PictureBox control is used to display and
scale images; the TextBox control can be used to easily display and edit single or
multiple lines of text.
• List Controls: The ListBox, ComboBox, and CheckListBox offer different interfaces
for displaying and manipulating data in a list format.
• ListView and TreeView Controls: The ListView offers multiple views for displaying
data items and their associated icons. The TreeView presents hierarchical
information in an easy-to-navigate tree structure.
• Timer and Progress Bar Controls: A timer can be used to control when an event is
invoked, a ProgressBar to visually monitor the progress of an operation.
• Building a User Control: When no control meets an application's needs, a custom
one can be crafted by combining multiple controls or adding features to an existing
one.
• Moving Data Between Controls: Drag and drop provides an easy way for users to
copy or move an item from one control to another. .NET offers a variety of classes
and events required to implement this feature.
• Using Resources: Resources required by a program, such as title, descriptive labels,
and images, can be embedded within an application's assembly or stored in
a satellite assembly. This is particularly useful for developing international
applications.
Windows Forms (WinForms) are not restricted to using the standard built-in controls.
Custom GUI controls can be created by extending an existing control, building a totally new
control, or fashioning a user control from a set of related widgets.
➢ Create windows Forms application:
1. File ➔ New ➔ Project ➔ Search C# Windows Forms App ➔ Next ➔ Give
descriptive name to the project ➔ Create ➔ will gives to you the following page
2. C# Windows Forms
Page 2 of 15
a. Toolbox : Container of controls
b. Form design
c. Properties of a control
d. Properties as you are seeing grouped as Accessibility, Appearance, Behavior
Data …
e. Event Like key press, key down, mouse hove , mouse up…
f. Project file by default it gives us these files only one form. When it is necessary to
and form Right click on the project ➔ Add ➔ New Items ➔ Form(Windows
Forms) ➔ Give descriptive name ➔ Add
g. Debugging area (start)
✓ How to add controls to the form in Design development way? There are two ways:
1. Drag from the toolbox and drop to the form or
2. Double click
✓ Change the default properties of controls:
When adding controls to the form the controls have default properties such as
name, text, color, font, size etc. There text and name properties are there name
increment by one if more than one the same control added to the form. For
example, Lebel will has Label, Label1, Label2 name and text property. Text
property is use to describe the control and name is use to bind data to the control.
When to give the name of the control prefacing by txt, btn, check, rad,rich of
Textbox, button, checkbox, radiobutton, ritchTextbox respectively can be
descriptive and easy to remember.
In the following example there are:
✓ 10 labels : their text property renamed to Emp Id, First Name , Last
Name, Gender, Educational Status, Age, Skills, Hire Date and Address.
3. C# Windows Forms
Page 3 of 15
Name in this example these labels are used to description only and no
need of name property.
✓ 3 textboxs: their name properties renamed to txtEmpId, txtFname and
txtLname.
✓ 2 radiobuttons : renamed as radMale and radFemale.
✓ 1 NumericUpDown: renamed as numAge
✓ 1 DatTimePicker : remade as dateTimeHireDate.
✓ 1 RichTextBox: renames as richAddress.
✓ 3 CheckBoxs : remaned as checkCpp, checkCSharp and checkJava.
✓ 5 Buttons : renamed as btnSave, btnUpdate, btnDelete, btnReferesh and
btnClear.
➢ These name properties are important for accessing data of the controls.
➢ Data Manipulation of controllers
A. Label : It uses to write description of other controls.
B. TextBox : To input data using textbox there is Text property. So, the name of
textbox.Text can accept text data and if you need another type of data you have to
convert using class of methods thus can convert it into appropriate format.
To display data on the textbox put textbox name. Text at left and text value at the
right as string or if the data is in another format convert it into string.
Some of properties you can change:
i. Multiline: True/False
ii. PasswordChar: *
iii. ReadOnly: True/False
iv. TabIndex: index number
C. RadioButton : To input data using radiobutton there is Checked property. So, the
name of radiobutton.Checked can accept data of any type you will give.
D. CheckBox : To input data using checkbox there is Checked property similar with
radiobutton. So, the name of checkbox.Checked can accept data of any type you
will give.
E. ComboBox :In combobox you can give static list of data as items collection or can
bind from other source like database. To add static list Right click ➔ Properties
➔Items ➔Collection ➔Add list in line break
F. GroupBox : It uses to grouping controls.
G. RichTexBox: Multi line text area control.
H. DataGridView : It uses to manipulate data in tabular format. Source of the data can
be any persistent source like database.
I. DatetimePicker : It uses to populate calendar and can pick and input easily.
J. MenuStrip: it uses to create navigation menu.
K. Button : uses to
a. To perform an action on data entered on a dialog (for example clicking
Search after entering some search criteria)
b. To open another dialog or application (for example, Help buttons)
4. C# Windows Forms
Page 4 of 15
1. Accept data of this form from the controls
There are predefined properties of each controls and default data types to accept
data from the controls even though it is possible to cast when necessary. For
example cast of NumericUpDown to int, int age = (int)numAge.Value;
No Control Property Default value
1 TextBox Text String
2 RadioButton Checked User can give
any value
3 ComboBox Text String
4 CheckBox Checked User can give
any value
5 DataTimePicker Text String
6 RichTextbox Text String
7 NumericUpDown Value Decimal
i. string fname = txtFname.Text;
ii. string lname = txtlname.Text;
iii. string gender = null;
if(radMale.Check)
{
gender=”Male”;
5. C# Windows Forms
Page 5 of 15
}
if(radFemale.Check)
{
gender=”Female”;
}
iv. string eduStatus = comEducationalStatus.Text;
v. int age = (int)numAge.Value;//Explicit cast of NumericUpDown to int
vi. string interest=null;
if(checkCSharp.Checked)
{
interest=”C# , ”;
}
if(checkJava.Check)
{
interest +=”Java , ”;
}
if(checkCpp.Check)
{
interest +=”C++ ”;
}
vii. string hire_date = txtDateTime.Text;
viii. string address = txtAddress.Text;
6. C# Windows Forms
Page 6 of 15
2. Persist these data using ADO.NET
ADO.NET is a data access technology from Microsoft .Net Framework , which provides
communication between relational and non-relational systems through a common set of
components . ADO.NET consist of a set of Objects that expose data access services to the
.NET environment. ADO.NET is designed to be easy to use, and Visual Studio provides
several wizards and other features that you can use to generate ADO.NET data access
code.
The two key components of ADO.NET are Data Providers and Dataset. The .Net
Framework includes mainly three Data Providers for ADO.NET. They are the
Microsoft SQL Server Data Provider, OLEDB Data Provider and ODBC Data Provider. SQL
Server uses the SqlConnection object, OLEDB uses the OleDbConnection Object and ODBC
uses OdbcConnection Object respectively.
The four Objects from the .Net Framework provides the functionality of Data Providers
in the ADO.NET. They are Connection Object, Command Object , DataReader Object
and DataAdapter Object. The Connection Object provides physical connection to the Data
Source. The Command Object uses to perform SQL statement or stored procedure to be
executed at the Data Source. The DataReader Object is a stream-based , forward-only,
read-only retrieval of query results from the Data Source, which do not update the data.
Finally the DataAdapter Object , which populate a Dataset Object with results from a Data
Source .
7. C# Windows Forms
Page 7 of 15
DataSet provides a disconnected representation of result sets from the Data Source, and it is
completely independent from the Data Source. DataSet provides much greater flexibility
when dealing with related Result Sets.
DataSet consists of a collection of DataTable objects that you can relate to each other with
DataRelation objects. The DataTable contains a collection
of DataRow and DataCoulumn Object which contains Data. The DataAdapter Object provides
a bridge between the DataSet and the Data Source.
i. Connect to the database (SQL Database)
The string in s use as Data Source string
To connect to the database .Net framework using System.Data.SqlClient; namespace
provides SqlConnection class take parameters Data Source, Initial Catalog and
Integrated security. Creating this connection object in class level is better for reuse
than creating in every method. And connection string built as follows:
SqlConnection conn = new SqlConnection("Data Source =DESKTOP-
N8EVIESSQLEXPRESS; Initial Catalog=Employee; Integrated Security=True;");
ii. Open connection: to open the connection there is Open () method in
SqlConnection class and call like as follows:
conn.Open();
iii. Query : So, now it is possible to insert data to the database or fetch data from the
database. To do this there is SqlCommand class and in this class there are methods
uses to execute the query such as ExecuteNonQuery ,ExecuteReader and
ExecuteScalar.
a. Insert to the database: according to the example when double click save
button private method generated. In this method can write the following code.
(INSERT, INTO, VALUES are keywords and filed name can be in back-tike or
empty like in the example. If field is in single quotation or double quotation it is
an error. For values can store on variable or use directly as an example).
8. C# Windows Forms
Page 8 of 15
string sqlInsert = "INSERT INTO tblEmployee
(EmpId,fname,lname,gender,educational_statu,age,skills,hire_date,address) VALUES
('"+empId+"','"+fname+"','"+lname+"','"+gender+"','"+comEduStatus.Text+"','"+age+
"','"+skills+"','"+dateTimeHireDate.Text+"','"+richAddress.Text+"')";
SqlCommand cmd = new SqlCommand(sqlInsert, conn);
int result = cmd.ExecuteNonQuery();
MessageBox.Show(result.ToString());
After input it is better to clear the controls and ready for new task.
//Clear controls
txtEmpId.Clear();
txtFname.Clear();
txtLname.Clear();
radMale.Checked = false;
radFemale.Checked = false;
comEduStatus.Text = "--Select Edu Status--";
numAge.Value = 0;
dateTimeHireDate.Text = "";
richAddress.Clear();
checkCpp.Checked = false;
checkCSharp.Checked = false;
checkJava.Checked = false;
b. Update query : Like save button when double clicking the private method
generate and can write the following code. And if the connection is closed
reopen it here.
conn.Open();
//Query
string sqlUpdate = "UPDATE tblEmployee SET fname='" +
txtFname.Text + "',lname='" + txtLname.Text + "',gender='" + gender +
"',educational_statu='" + comEduStatus.Text + "',age='" + age + "',skills='" +
skills + "',hire_date='" + dateTimeHireDate.Text + "',address='" +
richAddress.Text + "' WHERE EmpId ='"+txtEmpId.Text+"'";
SqlCommand cmd = new SqlCommand(sqlUpdate, conn);
int result = cmd.ExecuteNonQuery();
After update it is better to clear the controls and ready for new task.
//Clear controls
txtEmpId.Clear();
txtFname.Clear();
txtLname.Clear();
radMale.Checked = false;
radFemale.Checked = false;
comEduStatus.Text = "--Select Edu Status--";
numAge.Value = 0;
9. C# Windows Forms
Page 9 of 15
dateTimeHireDate.Text = "";
richAddress.Clear();
checkCpp.Checked = false;
checkCSharp.Checked = false;
checkJava.Checked = false;
c. Delete query: like above operations when double clicks delete button click
buttoned for delete will be generated and write the following code as well if
the connection is closed reopen here.
conn.Open();
string sqlDelete = "DELETE tblEmployee WHERE EmpId ='" +
txtEmpId.Text + "'";
SqlCommand cmd = new SqlCommand(sqlDelete, conn);
int result = cmd.ExecuteNonQuery();
if(result > 0)
{
MessageBox.Show("Deleted");
}
conn.Close();
d. Populate to the data grid view: this can be done when the form load. To do
this double click on the form and it will create the following method:
private void Form1_Load(object sender, EventArgs e)
{
}
Then write the following code in this method:
conn.Open();
string sql = " Select * from tblEmployee";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dgv.DataSource = dt;
conn.Close();
e. Fill the controls by data from the data grid view when click a row of the grid
view. To do this double click on the data grid view and create the following
method:
private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
Then write the following code in this method:
10. C# Windows Forms
Page 10 of 15
CurrentRow: DataGridView property get row of the data table created above
and load to the data grid view.
Cells: property to get the cell by its index value of the CurruntRow.
Example : dgv.CurrentRow.Cells[0].Value.ToString(); statement fetch the first row first
column data and txtEmpId.Text store the fetched data.
txtEmpId.Text = dgv.CurrentRow.Cells[0].Value.ToString();
txtFname.Text = dgv.CurrentRow.Cells[1].Value.ToString();
txtLname.Text = dgv.CurrentRow.Cells[2].Value.ToString();
string gender = dgv.CurrentRow.Cells[3].Value.ToString();
if (gender =="Male")
{
radMale.Checked = true;
}
if (gender =="Female")
{
radFemale.Checked = true;
}
comEduStatus.Text = dgv.CurrentRow.Cells[4].Value.ToString();
string age = dgv.CurrentRow.Cells[5].Value.ToString();
numAge.Value =Convert.ToInt32(age);
string skills = dgv.CurrentRow.Cells[6].ToString();
if (skills.Contains("C#"))
{
checkCSharp.Checked = true;
}
if (skills.Contains("Jave"))
{
checkJava.Checked = true;
}
if (skills.Contains("C++"))
{
checkCpp.Checked = true;
}
dateTimeHireDate.Text = dgv.CurrentRow.Cells[7].Value.ToString();
richAddress.Text = dgv.CurrentRow.Cells[8].Value.ToString();
f. Refresh: after insert, update or delete the data grid view cannot show update
synchronously. So, it is better to use is button.
conn.Open();
string sql = " Select * from tblEmployee";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dgv.DataSource = dt;
conn.Close();
11. C# Windows Forms
Page 11 of 15
v. Clear control: double click clear button and write the following code.
//Clear controls
txtEmpId.Clear();
txtFname.Clear();
txtLname.Clear();
radMale.Checked = false;
radFemale.Checked = false;
comEduStatus.Text = "--Select Edu Status--";
numAge.Value = 0;
dateTimeHireDate.Text = "";
richAddress.Clear();
checkCpp.Checked = false;
checkCSharp.Checked = false;
checkJava.Checked = false;
3. Add login form (not only login form you can add as you wish)
Right click on project ➔ Add ➔ New Item ➔ Form(Windows Form) ➔ named to loging
➔ Add
Add controls to the login form
Rename text properties like this and name properties as txtUsername, txtPassowrd,
btnLogin and btnClear. As well txtPassword PasswordChar as *.
Change the star from to login: open Program.cs ➔ Application.Run(new Form1());
check Form1 to login. Then when this project starts start from login form.
Check username and password and if its valued open user registration form.
Double click login button generates a method and compare username and password as
follows.
12. C# Windows Forms
Page 12 of 15
string username, password;
conn.Open();
username = txtUsername.Text;
string query = "select * from tblUsers " +
"WHERE username ='" + username + "' " +
"AND password ='" + txtPassword.Text + "'";
SqlDataReader row;
SqlCommand myCommand = new SqlCommand(query, conn);
row = myCommand.ExecuteReader();
//Check username and password
if (row.HasRows)
{
//read from database
if (row.Read())
{
username = row["username"].ToString();
password = row["password"].ToString();
}
//Create Form1 object
Form1 form1 = new Form1();
//call Show method of Forms class through above object
form1.Show();
}
4. Exception Handling: handling errors. Errors may happen because of different
causes. It may be trying to submit empty filed, spelling of name property, incorrect
connection parameter, out of index in array, division by zero etc. So, to handle such
errors .Net framework provide Exception class. In this class many exceptions are
defined and can handle as follows.
try
{
}
catch(Exception ex)
{
}
finally
{
}
In try block of code execute when true and exception will throw when error happened.
Finally block of code is not dependent on either try or catch block what ever the code
finally code block will be execute. So, the above codes can be in this try catch and validate
the code. For example save data can be validate as follows:
try
{
string empId = txtEmpId.Text;
string fname = txtFname.Text;
string lname = txtLname.Text;
int age = (int)numAge.Value;
string gender = null;
13. C# Windows Forms
Page 13 of 15
if (radMale.Checked)
{
gender = "Male";
}
if (radFemale.Checked)
{
gender = "Female";
}
string skills = null;
if (checkCSharp.Checked)
{
skills = "C# ";
}
if (checkJava.Checked)
{
skills += "Java ";
}
if (checkCpp.Checked)
{
skills += "C++";
}
//Open connection
conn.Open();
//Query
string sqlInsert = "INSERT INTO tblEmployee
(EmpId,fname,lname,gender,educational_statu,age,skills,hire_date,address)
VALUES
('"+empId+"','"+fname+"','"+lname+"','"+gender+"','"+comEduStatus.Text+"','"+
age+"','"+skills+"','"+dateTimeHireDate.Text+"','"+richAddress.Text+"')";
SqlCommand cmd = new SqlCommand(sqlInsert, conn);
int result = cmd.ExecuteNonQuery();
MessageBox.Show(result.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex.Message);
}
finally
{
conn.Close();
}
If error happened and get what specifically it is exception object can call a property
Message and able to see specific message. There may be database name error, table name
error, filed name error and handled in such way.
4.1. To validate whether textboxs are empty or not it is possible to validate by
conditional statement if they are must to have value. (When the button clicks i.e
click event)
14. C# Windows Forms
Page 14 of 15
If(txtEmpId.Text ==”” || txtFname .Text =”” || txtLname.Text ==””)
{
MessageBox.Show(“Fields must fill”,”Information”);
}
4.2. Validate RadioButton . if it is must to select one of the radio buttons. It is possible to
validated in such way and inform the user to select one of them.
if(radFemale.Checked == false || radMale.Checked == false)
{
MessageBox.Show("Must select gender", "Information");
}
4.3. Keypress event also can validate textbox and data type as follows :
5. private void txtFname_KeyPress(object sender, KeyPressEventArgs e)
6. {
7. if (Char.IsNumber(e.KeyChar) || Char.IsSymbol(e.KeyChar) ||
8. Char.IsWhiteSpace(e.KeyChar) || Char.IsPunctuation(e.KeyChar))
9. {
10. MessageBox.Show("Only Characters are
allowed","Warning");
11. e.Handled = true;
12. }
}
To generate this method right click First name textbox ➔ properties ➔ event
➔keyPress ➔ double click. Like this can validate last name to accept only
alphabet.
4.4. Validate Login operation as follows
13. try
14. {
15. conn.Open();
16. string username = txtUsername.Text;
17. string query = "select * from tblUsers " +
18. "WHERE username ='" + username + "' " +
19. "AND password ='" + txtPassword.Text + "'";
20.
21. if(txtUsername.Text =="" || txtPassword.Text =="")
22. {
23. MessageBox.Show("Fields Must be filled ");
24. }
25. SqlDataReader row;
26. SqlCommand myCommand = new SqlCommand(query, conn);
27. row = myCommand.ExecuteReader();
28.
29. if (row.HasRows)
30. {
31. if (row.Read())
32. {
33. username = row["username"].ToString();
34. password = row["password"].ToString();
35. }
15. C# Windows Forms
Page 15 of 15
36. Form1 form1 = new Form1();
37. form1.Show();
38. }
39. else
40. {
41. MessageBox.Show("Username and/or password nor matched ");
42. }
43. }
44. catch(Exception ex)
45. {
46. MessageBox.Show("Error " + ex.Message, "Information");
47. }
48. finally
49. {
50. conn.Close();
51. }
To sum-up create Windows Forms application (Desktop), add controls, customize their
properties, accept data through controls and to store permanently create connection to
the data source (SQL Server), open connection, write query, execute this query and close
connection. Validate data operations and change default start of the project. These
concepts are explained and practice by yourself.