How to delete row from gridview in asp.net?

Deleting a row data from a Gridview is a very simple. We can use Gridview's default OnRowDeleting method to delete. Let's do the task.
Hare is our HTML of Gridview:
             <asp:GridView runat="server" ID="GridView1" DataKeyNames="id"  class="table table-bordered" OnRowDeleting="GridView1_RowDeleting">
                   <Columns>                   
                         <asp:TemplateField  HeaderText="Delete">
                           <ItemTemplate>
                          <asp:Button ID="deleteButton" CssClass="btn btn-danger" runat="server" CommandName="Delete" Text="X" OnClientClick="return confirm('Are you sure you want to delete this Information?');" />
                           </ItemTemplate>
                       </asp:TemplateField>
                   </Columns>
             </asp:GridView>

Here is the code behind:
 private readonly SqlConnection con =
        new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=AjaxTestProject;Integrated Security=True;");
 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
            int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand("delete from tblCustomer where id=" + Id, con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
            GetCustomer();     
    } 
Our Layout:

No comments

Powered by Blogger.