posted 3/10/2009 by Sumit Arora
Today I would like to share with you how to update,delete and edit rows in GridView data control.Gridview has most of the events inbuilt so one can use these events to perform these operations.1.To edit a row in Gridview: To edit a row there is an event called RowEditing .
protected void gridView_RowEditing(object sender, GridViewEditEventArgs e) { gridView.EditIndex = e.NewEditIndex; // fetch and rebind the data. BindData(); }
2. To cancel and go back to the previous step.There is an event called RowCancelingEdit.
protected void gridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { gridView.EditIndex = -1; // fetch and rebind the data. BindData(); }
3.To update a row in Gridview:It can be done with the help of RowUpdating event of Gridview.
protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e) { //fetch datakey/primarykey for identifyning the row int UserID= Convert.ToInt32(gridView.DataKeys[e.RowIndex].Value); TextBox FirstName = (TextBox)gridView.Rows[e.RowIndex].Cells[1].Controls[1]; TextBox LastName = ((TextBox)gridView.Rows[e.RowIndex].Cells[2].Controls[1]); TextBox Address = ((TextBox)gridView.Rows[e.RowIndex].Cells[3].Controls[1]); TextBox City = ((TextBox)gridView.Rows[e.RowIndex].Cells[4].Controls[1]); SqlCommand com = new SqlCommand("update test set firstname='"+FirstName .Text+"',lastname='"+LastName .Text+"',address='"+Address .Text+"',city='"+City.Text+" 'where Key="+UserID+"",con); con.Open(); com.ExecuteNonQuery(); con.Close(); gridView.EditIndex = -1;//to go back to the previous position // fetch and rebind the data. BindData(); } />
/>
4. To delete a row from the gridview:It can be done with the help of RowDeleting event.
protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e) < { //fetch datakey/primarykey for identifyning the row int UserID= Convert.ToInt32(gridView.DataKeys[e.RowIndex].Value); SqlCommand com = new SqlCommand("Delete from test where Key="+UserID +"",con); con.Open(); com.ExecuteNonQuery(); con.Close(); // fetch and rebind the data. BindData(); }
In .aspx side you need to add a GridView data control.for update/delete you have to define the datakey in gridview at aspx side:
<asp:GridView ID="gridView" runat="server" DataKeyNames="Key" AutoGenerateColumns="False" OnRowCancelingEdit="gridView_RowCancelingEdit" OnRowDeleting="gridView_RowDeleting" OnRowEditing="gridView_RowEditing" OnRowUpdating="gridView_RowUpdating" >
This is all i have to tell about Update,Delete,Edit a row in GridView Data Control.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18