How to delete row in Gridview in Asp.Net - ProgramIdea

How To Delete GridView's Row In Asp.Net

Here we are binding a GridView in Asp.Net.

Points Of Remember:

1. Fire GridView's RowDeleting event.

2. Set GridView's AutoGenerateDeleteButton propery to True

3. Set GridView's DataKeyNames Property to record ID (ID=Primary/Unique key of student table)

4. Add namespace System.Data and System.Data.SqlClient in your C# page.

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"

            CellPadding="4" ForeColor="#333333" Width="600px" DataKeyNames="ID"

            AutoGenerateDeleteButton="True" OnRowDeleting="GridView1_RowDeleting">

            <Columns>

                <asp:BoundField DataField="Name" HeaderText="Name" />

                <asp:BoundField DataField="Branch" HeaderText="Branch" />

                <asp:BoundField DataField="City" HeaderText="City" />

            </Columns> 

            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />        

            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

        </asp:GridView>

    </div>

    </form>

</body>

</html>

C# Codes :

using System.Data;

using System.Data.SqlClient;

 

public partial class GridView_test_Delete : System.Web.UI.Page

{

    SqlConnection con = new SqlConnection( @"Data Source=JITESH-PC\SQL;Initial

                                                                                                        Catalog=db_Student;Integrated Security=True");

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindGridView();

        }

    }

    //method for binding GridView

    protected void BindGridView()

    {

        DataTable dt = new DataTable();

        SqlDataAdapter da = new SqlDataAdapter( "Select ID,Name,Branch,City from tbl_student" , con);

        con.Open();

        da.Fill(dt);

        con.Close();

 

        if (dt.Rows.Count > 0)

        {

            GridView1.DataSource = dt;

            GridView1.DataBind();

        }

    }

    // row delete event

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        // find student id of edit row

        string id = GridView1.DataKeys[e.RowIndex].Value.ToString();

 

        SqlCommand cmd = new SqlCommand( "delete from tbl_student where ID=" + id, con);

        con.Open();

        cmd.ExecuteNonQuery();

        con.Close();

 

        // Refresh the GridView

        BindGridView();

    }

}

Output:
demo