► Add the EditItemTemplate on each table field which you want to update at runtime for ex:
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox Text='<%# Eval("name") %>' ID="txtname" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="Server" Text='<%# Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
► Next Add add commandField in your gridview:
<asp:CommandField ButtonType="Button"
ShowDeleteButton="True" ShowEditButton="True"
ShowSelectButton="True" />
► Now Implement the events rowEditing, RowUpdating and rowCancelEdit to edit the gridview:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(((Label)GridView1.Rows[e.RowIndex].FindControl("lblid")).Text);//ID
string name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname")).Text;
SqlConnection connect = new SqlConnection(ConnString);
connect.Open();
string q = "Update table1 set name=@name where id=@id";
SqlCommand comm = new SqlCommand(q, connect);
comm.Parameters.AddWithValue("name", name);
comm.Parameters.AddWithValue("id", id);
comm.ExecuteNonQuery();
connect.Close();
GridView1.EditIndex = -1;
//BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
//BindGrid();
}