In code behind
protected void Page_Load(object sender, EventArgs e)
{
if
(!Page.IsPostBack)
{
bindgrid();
total = 0;
}
}
public void bindgrid()
{
SqlConnection conn
= new SqlConnection("Data Source='localhost';Initial
Catalog='Northwind';Integrated Security=SSPI;Persist Security Info=False ");
SqlCommand cmd =
new SqlCommand("select CategoryName,CategoryID from
Categories ", conn);
SqlDataAdapter da
= new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select CategoryName,CategoryID from
Categories", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
gdview.DataSource = ds.Tables[0].DefaultView;
gdview.DataBind();
}
protected void gdview_RowEditing(object sender, GridViewEditEventArgs e)
{
gdview.EditIndex = e.NewEditIndex;
bindgrid();
}
protected void gdview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int catid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());
string
strcatname=((TextBox)gdview.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
SqlConnection conn
= new SqlConnection("Data Source='localhost';Initial
Catalog='Northwind';Integrated Security=SSPI;Persist Security Info=False ");
SqlDataAdapter da
= new SqlDataAdapter("", conn);
conn.Open();
da.UpdateCommand = new SqlCommand("update Categories set CategoryName='" +
strcatname + "' where CategoryID=" + catid, conn);
da.UpdateCommand.ExecuteNonQuery();
conn.Close();
gdview.EditIndex = -1;
bindgrid();
}
protected void gdview_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gdview.EditIndex = -1;
bindgrid();
}
protected void gdview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int catid = int.Parse(gdview.DataKeys[0].Value.ToString());
SqlConnection conn
= new SqlConnection("Data Source='localhost';Initial
Catalog='Northwind';Integrated Security=SSPI;Persist Security Info=False ");
SqlDataAdapter da
= new SqlDataAdapter("", conn);
conn.Open();
da.DeleteCommand = new SqlCommand("delete from Categories where
CategoryID="+catid, conn);
da.DeleteCommand.ExecuteNonQuery();
conn.Close();
bindgrid();
}
In the gdview_RowEditing and gdview_RowDeleting
event, we have used the below code to retrieve categoryid from datakey of
GridView,
int catid =
int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());
Here, e. RowIndex represents the index of the
particular row.