[c#] How to delete row in gridview using rowdeleting event?

This is my .cs code :

protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
 Gridview1.DeleteRow(e.RowIndex);
 Gridview1.DataBind();
}

and this is markup,

<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" 
                                                AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting">
                    <Columns>
                    <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                    <asp:TemplateField HeaderText="Column Name">
                        <ItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>

                 <%-- <asp:TemplateField HeaderText="Header 2">
                        <ItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>--%>
                    <asp:TemplateField HeaderText="Data Type">
                        <ItemTemplate>
                              <asp:DropDownList ID="ddldatatype" runat="server">
                              <asp:ListItem>varchar</asp:ListItem>
                              <asp:ListItem>int</asp:ListItem>
                              <asp:ListItem>numeric</asp:ListItem>
                              <asp:ListItem>uniqueidentifier</asp:ListItem>
                              <asp:ListItem>char</asp:ListItem>
                              </asp:DropDownList>
                        </ItemTemplate>
                        <FooterStyle HorizontalAlign="Right" />
                        <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
                         <asp:Button ID="ButtonDel" runat="server" Text="Delete Row" OnClick="ButtonDel_Click" />
                         <input type="hidden" runat="server" value="0" id="hiddencount" />
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" >Delete</asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    </Columns>
            </asp:gridview>

Please sugegest me. I have done this much.. but still not deleting row...

 protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
         {


             //Gridview1.DeleteRow((int)Gridview1.DataKeys[e.RowIndex].Value);
             //Gridview1.DeleteRow(e.RowIndex);
             //Gridview1.DataBind();
             foreach(DataRow dr in dt.Rows)
             {
                 dt.Rows.Remove(dr);
                 dt.Rows[e.RowIndex].Delete();

             }
             Gridview1.DeleteRow(e.RowIndex);
            // dt = (DataTable)Gridview1.DataSource;
             Gridview1.DataSource = dt;
             Gridview1.DataBind();
       }

This question is related to c# asp.net

The answer is


     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = GridView1.SelectedIndex;
        int id = Convert.ToInt32(GridView1.DataKeys[index].Value);
        SqlConnection con = new SqlConnection(str);
        SqlCommand com = new SqlCommand("spDelete", con);
        com.Parameters.AddWithValue("@PatientId", id);
        con.Open();
        com.ExecuteNonQuery();

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index


The solution is somewhat simple; once you have deleted the row from the datagrid (Your code ONLY removes the row from the grid and NOT the datasource) then you do not need to do anything else. As you are doing a databind operation immediately after, without updating the datasource, you are re-adding all the rows from the source to the gridview control (including the row removed from the grid in the previous statement).

To simply delete from the grid without a datasource then just call the delete operation on the grid and that is all you need to do... no databinding is needed after that.


I know this is a late answer but still it would help someone in need of a solution. I recommend to use OnRowCommand for delete operation along with DataKeyNames, keep OnRowDeleting function to avoid exception.

<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" 
     AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting" OnRowCommand="Gridview1_RowCommand" DataKeyNames="ID">

Include DataKeyNames="ID" in the gridView and specify the same in link button.

<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("ID")%>'>Delete</asp:LinkButton>

protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Delete")
    {
      int ID = Convert.ToInt32(e.CommandArgument);
      //now perform the delete operation using ID value
    }
}

protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)    
{
//Leave it blank
}

If this is helpful, give me +


Make sure to create a static DataTable object and then use the following code:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    dt.Rows.RemoveAt(e.RowIndex); 
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

Here is a trick with what you want to achieve. I was also having problem like you.

Its hard to get selected row and data key in RowDeleting Event But it is very easy to get selected row and datakeys in SelectedIndexChanged event. Here's an example-

protected void gv_SelectedIndexChanged(object sender, EventArgs e)
{
        int index = gv.SelectedIndex;
        int vehicleId = Convert.ToInt32(gv.DataKeys[index].Value);
        SqlConnection con = new SqlConnection("-----");
        SqlCommand com = new SqlCommand("DELETE FROM tbl WHERE vId = @vId", con);
        com.Parameters.AddWithValue("@vId", vehicleId);
        con.Open();
        com.ExecuteNonQuery();
}

Add the below line in Page load,

ViewState["GetRecords"] = dt;

then try this,

protected void DeleteRows(object sender, GridViewDeleteEventArgs e)
{
   dt = ViewState["GetRecords"] as DataTable;
   dt.Rows.RemoveAt(e.RowIndex);
    dt.AcceptChanges();
    ViewState["GetRecords"] = dt;
    BindData();
}

If you Still have any problem, send the code in BindData() method


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    MySqlCommand cmd;
    string id1 = GridView1.DataKeys[e.RowIndex].Value.ToString();
    con.Open();
    cmd = new MySqlCommand("delete from tableName where refno='" + id1 + "'", con);
    cmd.ExecuteNonQuery();
    con.Close();
    BindView();
}
private void BindView()
{
    GridView1.DataSource = ms.dTable("select * from table_name");
    GridView1.DataBind();
}

See the following code and make some changes to get the answer for your question

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    void CustomersGridView_RowDeleting
        (Object sender, GridViewDeleteEventArgs e)
    {
        TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
        if (cell.Text == "Beaver")
        {
            e.Cancel = true;
            Message.Text = "You cannot delete customer Beaver.";
        }
        else
        {
            Message.Text = "";
        }
    }  

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>GridView RowDeleting Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>
        GridView RowDeleting Example
    </h3>
    <asp:Label ID="Message" ForeColor="Red" runat="server" />
    <br />
    <asp:GridView ID="CustomersGridView" runat="server" 
        DataSourceID="CustomersSqlDataSource" 
        AutoGenerateColumns="False"
        AutoGenerateDeleteButton="True" 
        OnRowDeleting="CustomersGridView_RowDeleting"
        DataKeyNames="CustomerID,AddressID">
        <Columns>
            <asp:BoundField DataField="FirstName" 
                HeaderText="FirstName" SortExpression="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" 
                SortExpression="LastName" />
            <asp:BoundField DataField="City" HeaderText="City" 
                SortExpression="City" />
            <asp:BoundField DataField="StateProvince" HeaderText="State" 
                SortExpression="StateProvince" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="CustomersSqlDataSource" runat="server"
        SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID, 
            SalesLT.CustomerAddress.AddressID, 
            SalesLT.Customer.FirstName, 
            SalesLT.Customer.LastName, 
            SalesLT.Address.City, 
            SalesLT.Address.StateProvince 
            FROM SalesLT.Customer 
            INNER JOIN SalesLT.CustomerAddress 
            ON SalesLT.Customer.CustomerID = 
                SalesLT.CustomerAddress.CustomerID 
            INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID = 
                SalesLT.Address.AddressID"
        DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID = 
            @CustomerID and AddressID = @AddressID" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>">
        <DeleteParameters>
            <asp:Parameter Name="AddressID" />
            <asp:Parameter Name="CustomerID" />
        </DeleteParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>

Your delete code looks like this

Gridview1.DeleteRow(e.RowIndex);
Gridview1.DataBind();

When you call Gridview1.DataBind() you will populate your gridview with the current datasource. So, it will delete all the existent rows, and it will add all the rows from CustomersSqlDataSource.

What you need to do is delete the row from the table that CustomersSqlDataSource querying.

You can do this very easy by setting a delete command to CustomersSqlDataSource, add a delete parameter, and then execute the delete command.

CustomersSqlDataSource.DeleteCommand = "DELETE FROM Customer Where CustomerID=@CustomerID"; // Customer is the name of the table where you take your data from. Maybe you named it different 
CustomersSqlDataSource.DeleteParameters.Add("CustomerID", Gridview1.DataKeys[e.RowIndex].Values["CustomerID"].ToString());
CustomersSqlDataSource.Delete();
Gridview1.DataBind();

But take into account that this will delete the data from the database.


The easiest way is to create your GridView with some data source in ASP and call that data source in Row_Deletinng Event. For example if you have SqlDataSource1 as your GridView data source, your Row_Deleting event would be:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
      int ID = int.Parse(GridView1.Rows[e.RowIndex].FindControl("ID").toString());
      string delete_command = "DELETE FROM your_table WHERE ID = " + ID;
      SqlDataSource1.DeleteCommand = delete_command;
}

//message box before deletion
protected void grdEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach (DataControlFieldCell cell in e.Row.Cells)
        {
            foreach (Control control in cell.Controls)
            {
                LinkButton button = control as LinkButton;
                if (button != null && button.CommandName == "Delete")
                    button.OnClientClick = "if (!confirm('Are you sure " +
                           "you want to delete this record?')) return false;";
            }
        }
    }
}

//deletion
protected void grdEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    conn.Open();
    int empid = Convert.ToInt32(((Label)grdEmployee.Rows[e.RowIndex].Cells[0].FindControl("lblIdBind")).Text);
    SqlCommand cmdDelete = new SqlCommand("Delete from employee_details where id=" + empid, conn);
    cmdDelete.ExecuteNonQuery();
    conn.Close();
    grdEmployee_refreshdata();

}

If I remember from your previous questions, you're binding to a DataTable. Try this:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    DataTable sourceData = (DataTable)GridView1.DataSource;

    sourceData.Rows[e.RowIndex].Delete();

    GridVie1.DataSource = sourceData;
    GridView1.DataBind();
}

Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.


In Grid use this code having ID as your Primary Element so to uniquely identify each ROW

<asp:TemplateField>
            <ItemTemplate>
            <asp:HiddenField ID="Hf_ID" runat="server" Value='<%# Eval("ID") %>' />
            </ItemTemplate>
</asp:TemplateField>

and to search the uique ID use the code in C# code behind (basically this is searching hidden field and storing it in a var)

protected void Grd_Registration_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        var ID = (HiddenField)Grd_Registration.Rows[e.RowIndex].FindControl("ID");
        //Your Delete Logic Goes here having ID to delete

        GridBind();

    }

I think you are doing same mistake of rebinding as mentioned in this link

How to delete row from gridview?


Try This Make sure You mention Datakeyname which is nothing but the column name (id) in your designer file

//your aspx code

<asp:GridView ID="dgUsers" runat="server" AutoGenerateSelectButton="True" OnDataBound="dgUsers_DataBound" OnRowDataBound="dgUsers_RowDataBound" OnSelectedIndexChanged="dgUsers_SelectedIndexChanged" AutoGenerateDeleteButton="True" OnRowDeleting="dgUsers_RowDeleting" DataKeyNames="id" OnRowCommand="dgUsers_RowCommand"></asp:GridView>

//Your aspx.cs Code

protected void dgUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            int id = Convert.ToInt32(dgUsers.DataKeys[e.RowIndex].Value);
            string query = "delete from users where id= '" + id + "'";
            //your remaining delete code
        }

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
    SqlCommand cmd = new SqlCommand("Delete From userTable (userName,age,birthPLace)");
    GridView1.DataBind();
}