How to edit and Delete records in a gridview using datakeys

< asp:GridView ID="gdview" runat="server" ShowFooter="true" AutoGenerateColumns="False" DataKeyNames="CategoryID" OnRowCancelingEdit="gdview_RowCancelingEdit" OnRowDeleting="gdview_RowDeleting" OnRowEditing="gdview_RowEditing" OnRowUpdating="gdview_RowUpdating" Width="100%" AllowPaging="True" PageSize="5" OnPageIndexChanging="gdview_PageIndexChanging" OnRowDataBound="gdview_RowDataBound" >
< Columns >
< asp:BoundField HeaderText="Category Name" DataField="CategoryName" SortExpression="CategoryName" >
< ItemStyle Height="20px" Width="150px" />
< /asp:BoundField >

< asp:CommandField ShowEditButton="True" >
< ItemStyle Width="100px" />

<asp:TemplateField>
< ItemTemplate >
< asp:LinkButton ID="lnkdel" runat="server" Text="Delete" CommandName="Delete" >


<ItemStyle Width="100px" />





< /asp:GridView>



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();
}

Posted in |