Edit and Update records of Gridview

In this post I am trying to edit and update the records of the gridview.

First make sure edit button of the grideview is true and then write the code inside the "RowEditing" event of the grid.
protected void gdView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gdView.EditIndex = e.NewEditIndex;

            DataTable dt = (DataTable)ViewState["GrdData"];

            gdView.DataSource = dt;
            gdView.DataBind();
            ViewState["GrdData"] = dt;

        }
if you run and click edit button, you can see that the row of  gridview is in edit mode displaying update and cancel button on it.

In this step, it should implement the code for update button, so that save the changes in viewstate. Write the code inside the "RowUpdating" event of the grid
protected void gdView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DataTable dt = ViewState["GrdData"] as DataTable;
            GridViewRow row = gdView.Rows[e.RowIndex];
           dt.Rows[row.DataItemIndex]["Name"] = ((TextBox)                                  (row.Cells[1].Controls[0])).Text;
          dt.Rows[row.DataItemIndex]["Address"] = ((TextBox)                                  (row.Cells[2].Controls[0])).Text;
               dt.Rows[row.DataItemIndex]["Gender"] = ((TextBox)                                             (row.Cells[3].Controls[0])).Text;
            gdView.EditIndex = -1;
            gdView.DataSource = dt;
            gdView.DataBind();
            ViewState["GrdData"] = dt;

        }
If you have any doubts, watch my video here is the link
http://youtu.be/OfLRC8w21FU

Enjoy this...!
Happy coding...!

No comments:

Post a Comment