taher
In this article we will be discussing how to develop softwares for windows desktop application using .net Form technologies using C# sharp . We will be completing task of our old student details system . If you hadn't know it . Kindly go to this link and know which task we will complete in this exmple . It Basically contains CRUD Operation
Requirements for this example
Environment
We can Make Desktop application using many different technologies some is by microsoft and some are by other companies also . We will be discussing one of the most popular technology used to make windows Desktop software . We will be using Windows Form technology . We will complete task of our student details system . To know more about task click here . In Windows Form Each form has two section one is designer Part and one is implementation part or some calls it back end part or code writing section .
For Creating New Project in Visual Studio you need to go the files and click on new and from there to new Project . Give Name as WindowsFormApplication . As you create project visual studio creates for you one default form name as form1.designer and its respective Code writing section name as form1.cs.
We will be Following Steps below to complete our Task
DATABASE CREATION IN SQL
1.Go to microsoft sql management studio . There you need to enter Server Name our is .\SQLExpress and click connect .
2.Create New Database
3 Create Table
a.Create New Table By designing
b.Create Table by SQL Query
DESIGNING OF WINDOWS FORM IN VISUAL STUDIO
1.We will Design our application how user will look it. For designing part we will be using forms default toolbox and using drag and drop functionality of designer to place different component to the screen . We will placing labels and Textbox and Buttons for inputs and dataGridView for viewing already entered students in the database .
2.After you Placed all components properly in the screen . You need to provides its Name and Text to labels and Textbox so that you can access those component behind code in form1.cs to populate and Manipulate through programming .
3.Then we will assigning Events to component . Events means handling user interaction with our software
4.Then we will configure datagridview
Following Video will demonstrate the procedure of Designing and assigning Name , Text and events to it
Code Writing Part
Code Writing part is done in form1.cs file which is under Form1 in solution Explorer Right hand side . In This part we will learn how to fetch data from the server using SQL Queries and how to manipulate data before showing to the user . In This Part we will Learn how to insert , Update and Delete Data from Database using C Form using Sql Statements and Execute it .
1.Firstly We will create function to open Connection to database . This connection will be used to execute sql query in database. For use Configuration Manager .kindly Add Reference . System.Configuration in solution Explorer.
public SqlConnection ConnectionOpen()
{
string connectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.StudentsDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
return con;
}
"WindowsFormsApplication2.Properties.Settings.StudentsDBConnectionString"
to your connection string .2.We will Complete Insert Task . Insert Task is accomplished when user clicks on Insert Button in the Designing . Means First you need bind click event to Insert Button . Which we have already done . Due to our above action new function is create Behind code . In That function we to write following code . Copy the below code
INSERT
if (NameTextBox.Text == "" || AddressTextBox.Text == "" || TelephoneTextBox.Text == "" || StandardTextBox.Text == "" || rollNumberTextbox.Text == "")
{
MessageBox.Show("Kindly Enter All fields");
}
else
{
try
{
SqlConnection con = ConnectionOpen();
con.Open();
String selectSql = "INSERT INTO [StudentsDB].[dbo].[student_table] ([Name],[Address],[Telephone],[Standard],[Roll_Number]) VALUES
('"+NameTextBox.Text+"','"+AddressTextBox.Text+"','"+TelephoneTextBox.Text+"','"+StandardTextBox.Text+"','"+rollNumberTextbox.Text+"')";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.ExecuteNonQuery();
// SqlDataReader r1 = cmd.ExecuteReader();
this.studentsDBDataSet.student_table.AcceptChanges();
this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
clearTextBox();
}
catch (Exception p)
{
MessageBox.Show(p.ToString());
}
}
In the above code we have first open the sql connection and the write query in selectSql string and then initiate SqlCommand with query string and connection then execute it . We have then apply changes to datagridview by executing AcceptChanges and againing filling datagridview . ClearTextBox is function we have defined to clear all text box .
public void clearTextBox()
{
NameTextBox.Text = "";
AddressTextBox.Text = "";
TelephoneTextBox.Text = "";
rollNumberTextbox.Text = "";
StandardTextBox.Text = "";
student_id = "";
}
Then We will write event Selection Change in datagridView to select particular record to Update
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
if (selectedRow != null)
{
NameTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Name.ToString();
AddressTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Address.ToString();
TelephoneTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Telephone.ToString();
rollNumberTextbox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Roll_Number.ToString();
StandardTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Standard.ToString();
student_id = this.studentsDBDataSet.student_table[selectedrowindex].student_id.ToString();
}
}
Above We have First we have taken selected row Index which is selected . Then we have taken all information from dataset to different fields through field name and assign studend_id which variable we create . And which we will use to update database records .
UPDATE
3.To Complete UPDATE task . First we have to select row which we want to update . After that we will click update . Update code is given below
if (NameTextBox.Text == "" || AddressTextBox.Text == "" || TelephoneTextBox.Text == "" || StandardTextBox.Text == "" || rollNumberTextbox.Text == "")
{
MessageBox.Show("Kindly Enter All fields");
}
else
{
try
{
SqlConnection con = ConnectionOpen();
con.Open();
String selectSql = "UPDATE student_table SET Name='" + NameTextBox.Text + "',Address='" + AddressTextBox.Text + "',Telephone='" + TelephoneTextBox.Text + "',Standard='" +
StandardTextBox.Text + "',Roll_Number='" + rollNumberTextbox.Text + "' WHERE student_id='"+student_id+"'";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.ExecuteNonQuery();
// SqlDataReader r1 = cmd.ExecuteReader();
this.studentsDBDataSet.student_table.AcceptChanges();
this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
clearTextBox();
}
catch (Exception p)
{
MessageBox.Show(p.ToString());
}
}
We have done same things as above in Insert Just Changes SQL Statement
DELETE
To Delete a record you need to first select that record and then click delete button to delete that record .
if (student_id== "")
{
MessageBox.Show("Kindly Select Rows from to delete ?");
}
else
{
try
{
SqlConnection con = ConnectionOpen();
con.Open();
String selectSql = "DELETE FROM [StudentsDB].[dbo].[student_table] WHERE student_id='" + student_id + "'";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.ExecuteNonQuery();
// SqlDataReader r1 = cmd.ExecuteReader();
this.studentsDBDataSet.student_table.AcceptChanges();
this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
clearTextBox();
}
catch (Exception p)
{
MessageBox.Show(p.ToString());
}
}
Full Code is Given below . Kindly not forget to change equivalents Name you have given.
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;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
publicpartial class Form1 : Form
{
string student_id = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
SqlConnection con = ConnectionOpen();
}
public void clearTextBox()
{
NameTextBox.Text = "";
AddressTextBox.Text = "";
TelephoneTextBox.Text = "";
rollNumberTextbox.Text = "";
StandardTextBox.Text = "";
student_id = "";
}
private void NameTextBox_TextChanged(object sender, EventArgs e)
{
}
public SqlConnection ConnectionOpen()
{
string connectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.StudentsDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
return con;
}
private void button1_Click(object sender, EventArgs e)
{
if(NameTextBox.Text== "" || AddressTextBox.Text== "" || TelephoneTextBox.Text== "" || StandardTextBox.Text== "" || rollNumberTextbox.Text== "")
{
MessageBox.Show("Kindly Enter All fields");
}
else
{
try
{
SqlConnection con = ConnectionOpen();
con.Open();
String selectSql = "INSERT INTO [StudentsDB].[dbo].[student_table] ([Name],[Address],[Telephone],[Standard],[Roll_Number]) VALUES ('"+NameTextBox.Text+"','"+AddressTextBox.Text+"','"+TelephoneTextBox.Text+"','"+StandardTextBox.Text+"','"+rollNumberTextbox.Text+"')";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.ExecuteNonQuery();
// SqlDataReader r1 = cmd.ExecuteReader();
this.studentsDBDataSet.student_table.AcceptChanges();
this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
clearTextBox();
}
catch(Exception p)
{
MessageBox.Show(p.ToString());
}
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
if(selectedRow !=null)
{
NameTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Name.ToString();
AddressTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Address.ToString();
TelephoneTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Telephone.ToString();
rollNumberTextbox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Roll_Number.ToString();
StandardTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Standard.ToString();
student_id = this.studentsDBDataSet.student_table[selectedrowindex].student_id.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if(NameTextBox.Text== "" || AddressTextBox.Text== "" || TelephoneTextBox.Text== "" || StandardTextBox.Text== "" || rollNumberTextbox.Text== "")
{
MessageBox.Show("Kindly Enter All fields");
}
else
{
try
{
SqlConnection con = ConnectionOpen();
con.Open();
String selectSql = "UPDATE student_table SET Name='" + NameTextBox.Text + "',Address='" + AddressTextBox.Text + "',Telephone='" + TelephoneTextBox.Text + "',Standard='" + StandardTextBox.Text + "',Roll_Number='" + rollNumberTextbox.Text + "' WHERE student_id='"+student_id+"'";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.ExecuteNonQuery();
// SqlDataReader r1 = cmd.ExecuteReader();
this.studentsDBDataSet.student_table.AcceptChanges();
this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
clearTextBox();
}
catch(Exception p)
{
MessageBox.Show(p.ToString());
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if(student_id== "")
{
MessageBox.Show("Kindly Select Rows from to delete ?");
}
else
{
try
{
SqlConnection con = ConnectionOpen();
con.Open();
String selectSql = "DELETE FROM [StudentsDB].[dbo].[student_table] WHERE student_id='" + student_id + "'";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.ExecuteNonQuery();
// SqlDataReader r1 = cmd.ExecuteReader();
this.studentsDBDataSet.student_table.AcceptChanges();
this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
clearTextBox();
}
catch(Exception p)
{
MessageBox.Show(p.ToString());
}
}
}
}
}