Wednesday, November 30, 2011

Row edit,delete,update in grid view in asp.net using c#

Edit,Delete,Update Data in Grid view using Asp.net:
In previous posts i have given how to export grid view data to excel in asp.net and how to bind data to dropdownlist in grid view. Basically the grid view has properties( AutogenerateDeleteButton,AutogenerateEditButton,AutogenerateUpdateButton) to enable the auto generate Edit,Delete,Update buttons. Here i will given  how to perform the all functions on grid view records.
Grid View properties:
 <asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateSelectButton="True">
 </asp:GridView>

Bind the data to grid view:
//page load event
if(page.isPostback==false)
{
dataset ds=null;
ds=(dataset)session["ds1"];
//session will contain dataset ds1 with data selected by user
if(ds!=null)
{
gvemp.datasource=ds.Tables["employee"];
gvemp.DataBind();
}
}      
Row Editing:
When user clicks on edit button post backtakes place,row editing event of grid view will be executed.This event will provide row index
protected void gremp_rowediting(object sender,EventArgs e)
{
dataset ds=(dstaset)session["ds1"];
gvemp.editindex=e.new editindex;
//e.newedit index:- will be provide index of row for which edit button is selected
gvemp.Datasource=Ds.Table["employee"];
gvemp.Databind();
}
Row Updating:
This will perform post back,row-updating event procedure of grid view will be executed
protected void gvemp-rowupdating(Object sender,EvenArgs e)
{
Textbox txt=(Textbox)gvemp.Rows[e.RowIndex].cells[3].controls[0];
//here i will update the third cell data in grid view
int avg=int.parse(txt.Text);
Dataset ds=(dataset)session["ds1"]; 
ds.Tables["employee"].rows[e.Rowindex]["Average"]=avg;
ds.Tables["employee"].AcceptChanges();
session["Ds1"]=ds;
//it will overwrite the session of Dataset
//Rearrange Gridview
gvemp.editIndex=-1;
gvemp.Datasource=Ds.Tables["employee"];
gvemp.DataBind();
}
Row Deleting:
This will perform post back,row-deleting event procedure of grid view will be executed
protected void gvemp-rowdeleting(Object sender,EvenArgs e)
{
Dataset ds=(dataset)session["ds1"]; 
ds.Tables["employee"].rows[e.Rowindex].Delete();
ds.Tables["employee"].AcceptChanges();
session["Ds1"]=ds;
gvemp.Datasource=Ds.Tables["employee"];
gvemp.DataBind();
}

Post a Comment