DataGridView is a control
which is widely used in developing window application. DataGridView is an efficient
way through which we can display database table data into customizable format
that is where we can edit information, delete information, insert information
or update information indirectly from original database and after the user
confirmation these changes reflects into the original database. DataGridView
control helps to display data into customizable grid. DataGridView control provides
the flexibility to show data, modify data and much more with flexible tabular
format.
Here I am using a datagridview control with different
functionality such as update, delete, insert and much more. Let’s see a brief
description of example.
Step 1: First open visual studio and click on file menu
and select new project and then click project for window application.
Step 2: After Successful creating a new project then
drag datagridview control from toolbox and drop it into window form where you
want to use it.
Here I making window form with design which are appears as;

After successful design of window form write the following code to perform the action according to buttons.
public partial class Welcome : Form
{
/// <summary>
/// declare the varraible to use in different mode
/// </summary>
boolcheck=false;
SqlDataAdapter da;
SqlConnection con;
DataTable dt;
intindex ;
stringtxt_Name;
stringtxt_Address;
stringtxt_Designation;
stringtxt_Department;
publicWelcome()
{
InitializeComponent();
/// validation error message visibility false
label2.Visible= false;
/// bind table data with data grid view
DataBind();
/// disable the update button at form loading time
btn_Update.Enabled= false;
}
/// <summary>
/// Data bind method use to bind table data with datagrid view
/// </summary>
public voidDataBind()
{
/// bind database table data with datagrid view
con=newSqlConnection(ConnectionString.connString());
con.Open();
da=newSqlDataAdapter();
da.SelectCommand= newSqlCommand("Select * from tblGridView",con);
/// create sqlcommandbuilder to update, delete etc. in data grid view
SqlCommandBuilder cmdbuilder= new SqlCommandBuilder(da);
// data table to hold table data
dt=newDataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
/// define all column of datagrid view readonly
ReadOnlyGrid();
}
/// <summary>
/// readonlygrid method use to declare all cell of datagridview is read only
/// </summary>
public voidReadOnlyGrid()
{
// define all cell datagrid view readonly
for (inti=0; i<dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].ReadOnly= true;
}
}
/// <summary>
/// this method use to make empty the text field
/// </summary>
public voidEmptyField()
{
// make empty all text field
textBox1.Enabled= true;
TextBox[] txtName= { textBox1, textBox2, textBox3, textBox4, textBox5 };
for (inti=0; i<txtName.Length; i++)
{
txtName[i].Text=String.Empty;
}
}
/// <summary>
/// validate the user to input integer value only
/// </summary>
private void textBox1_Validating(objectsender, CancelEventArgse)
{
/// validating event of textbox when user input userid value
try
{
if (textBox1.Text!= "")
{
int num= Convert.ToInt32(textBox1.Text);
if (num>0&&num<=9999)
{
check=true;
label2.Text=String.Empty;
}
else { label2.Visible=true; }
}
}
catch (Exception ae)
{
label2.Visible=true;
}
}
/// <summary>
/// After the Succesful validating user here hide error message
/// </summary>
private void textBox1_Validated(objectsender, EventArgse)
{
/// check after the validating event userid validation
if (check)
{
label2.Visible=false;
label2.Text=String.Empty;
}
}
/// <summary>
/// this method help to insert data into sql table
/// </summary>
private void btn_Insert_Click(objectsender, EventArgse)
{
// insert new record
try
{
/// check any field if empty
if (textBox1.Text== ""||textBox2.Text==""||textBox3.Text ==""||textBox4.Text==""|| textBox5.Text=="")
{
MessageBox.Show("Please fill all enteries");
}
// check if validation message are showing
else if (label2.Text!= "")
{
MessageBox.Show("Userid must be integer value");
}
else
{
// insert new record and bind with database table
/// aoss the parameter in stored procedure gridviewtest
SqlCommand cmd= new SqlCommand("GridviewTest", con);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Userid", textBox1.Text);
cmd.Parameters.AddWithValue("@Name", textBox2.Text);
cmd.Parameters.AddWithValue("@Address", textBox3.Text);
cmd.Parameters.AddWithValue("@Designation", textBox4.Text);
cmd.Parameters.AddWithValue("@Department", textBox5.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Successfully inserted");
// bind table data with gridview
DataBind();
// make empty text field
EmptyField();
}
}
catch (Exception ae) { MessageBox.Show(ae.ToString().Substring(0,148)); }
}
/// <summary>
/// this method help to update data of existing information
/// </summary>
private void btn_Update_Click(objectsender, EventArgse)
{
try
{
/// update existing information
/// check if any textfield is empty
if ((textBox2.Text== ""||textBox3.Text==""||textBox4.Text ==""||textBox5.Text==""))
{
MessageBox.Show("Fill all enteries");
}
/// if no modification has been changed
else if (txt_Name== textBox2.Text&&txt_Address==textBox3.Text &&txt_Designation==textBox4.Text&& txt_Department==textBox5.Text)
{
}
else
{
/// update information by calling gridviewupdate stored procedure
SqlCommand cmd= new SqlCommand("GridviewUpdate", con);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Userid", textBox1.Text);
cmd.Parameters.AddWithValue("@Name", textBox2.Text);
cmd.Parameters.AddWithValue("@Address", textBox3.Text);
cmd.Parameters.AddWithValue("@Designation", textBox4.Text);
cmd.Parameters.AddWithValue("@Department", textBox5.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Successfully updated");
DataBind();
EmptyField();
}
}
catch (Exception ae) { MessageBox.Show(ae.ToString()); }
}
/// <summary>
/// this method fill all the existing data when double click on datagridview row header to update data
/// </summary>
private void dataGridView1_RowHeaderMouseDoubleClick(objectsender, DataGridViewCellMouseEventArgse)
{
/// update existing information by double click on rowheader of datagridview
btn_Update.Enabled= true;
btn_Delete.Enabled= false;
btn_Insert.Enabled= false;
textBox1.Text=dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
textBox2.Text=dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_Name=textBox2.Text;
textBox3.Text=dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txt_Address=textBox3.Text;
textBox4.Text=dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
txt_Designation=textBox4.Text;
textBox5.Text=dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
txt_Department=textBox5.Text;
textBox1.Enabled= false;
}
/// <summary>
/// cancel button method to disable or enable button
/// </summary>
private voidbtn_Edit_Click(objectsender, EventArgse)
{
/// event when clicked on cancel button
btn_Update.Enabled= false;
btn_Insert.Enabled= true;
btn_Delete.Enabled= true;
EmptyField();
}
/// <summary>
/// Delete existing record when clicked on dalete button either select single row or multiple row
/// </summary>
private void btn_Delete_Click(objectsender, EventArgse)
{
// check if multiple row selected for delete
if(dataGridView1.SelectedRows.Count>1)
{
/// show message box with notification to delete data from table
string messageText= "Do you want to permanent delete these data";
string caption= "Delete Records";
MessageBoxButtonsbutton=MessageBoxButtons.OKCancel;
if (MessageBox.Show(messageText, caption, button) == DialogResult.OK)
{
foreach (DataGridViewRow dr indataGridView1.SelectedRows)
{
int val= Convert.ToInt32(dr.Cells["Userid"].Value.ToString());
SqlCommand cmd= new SqlCommand("GridViewDelete", con);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@userid", val);
cmd.ExecuteNonQuery();
}
DataBind();
}
}
else
{
/// if one row select for delete
if (index>0)
{
string messageText= "Do you want to permanent delete data";
string caption= "Delete Records";
MessageBoxButtonsbutton=MessageBoxButtons.OKCancel;
/// check confirmation of user to delete data from table
if (MessageBox.Show(messageText, caption, button) == DialogResult.OK)
{
SqlCommand cmd= new SqlCommand("GridViewDelete", con);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@userid", index);
cmd.ExecuteNonQuery();
DataBind();
index=0;
}
}
else if(dataGridView1.Rows.Count <=0)
{
// grid view have no record
MessageBox.Show("No data found to delete ");
}
else
{
MessageBox.Show("Select row to delete data");
}
}
}
/// <summary>
/// this method fire when singleclick on datagridview row header, it is used for delete single row
/// </summary>
private void dataGridView1_RowHeaderMouseClick(objectsender, DataGridViewCellMouseEventArgse)
{
/// row select for delete data form data table
index=Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Userid"].Value.ToString());
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgse)
{
// set index value in every cell click event
index=0;
}
}
After Write the above codes debugs the program and perform the action.

Now insert the information

When you click on insert button then a confirmation message box open and when you click on ok button then new record will be shown into datagridview.

Now in the same manner you can perform all action like update, delete etc.
Leave Comment