How to Edit / Delete Data using Datagridview in .NET?
In this article I am going to explain about how to Edit and delete data through data grid view. Instead of writing loop here I get only modified row and update in the sql server table.
Description :
In windows application we can edit and delete data using datagridview itseld it is easy compare to other control. Here I load all data in data grid view and update through that datagridview.
Mainly I am not using any loop to get modified data simpley using dt.GetChanegs() method to get only modified data and update it. Design side
I have placed one datagridview and two button to update and delete like below
Server side
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataTable dt = new DataTable();
DataRow dr;
int rindex;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dt.Columns.Add("eno");
dt.Columns.Add("empname");
dt.Columns.Add("sal");
dr = dt.NewRow();
dr["eno"] = "101";
dr["empname"] = "Ravindran";
dr["sal"] = "45000";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["eno"] = "102";
dr["empname"] = "Mike";
dr["sal"] = "25000";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["eno"] = "103";
dr["empname"] = "James";
dr["sal"] = "33000";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["eno"] = "104";
dr["empname"] = "Allen";
dr["sal"] = "45000";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["eno"] = "105";
dr["empname"] = "Andrew";
dr["sal"] = "18000";
dt.Rows.Add(dr);
dt.AcceptChanges();
dataGridView1.DataSource = dt;
}
private void btnDelete_Click(object sender, EventArgs e)
{
string eno = dataGridView1.Rows[rindex].Cells[0].Value.ToString();
//using eno to delete records from database table
}
private void btnModify_Click(object sender, EventArgs e)
{
DataTable dtmod = new DataTable();
//here we can lod only modifed data rows in the new data table
dtmod = dt.GetChanges();
for (int i = 0; i <= dtmod.Rows.Count - 1; i++)
{
//here you can get updated row details and update in sql server database
}
}
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
rindex = e.RowIndex;
}
}
}
Here see this image only get updated recordSource code:
Client Side: Form Design
Code Behind: C#Conclusion
I hope this code snippet is help you to know about datagridview edit / update operations in windows application.