如何使用rowdeleting事件删除gridview中的行?

时间:2011-08-29 05:48:54

标签: c# asp.net

这是我的.cs代码:

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

这是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>

请认真我。我做了这么多..但仍然没有删除行...

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

16 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:7)

确保创建静态DataTable对象,然后使用以下代码:

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

答案 2 :(得分:3)

您的删除代码如下所示

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

当您调用Gridview1.DataBind()时,您将使用当前数据源填充gridview。因此,它将删除所有现有行,并将添加 CustomersSqlDataSource 中的所有行。

您需要做的是从CustomersSqlDataSource查询的表中删除该行。

您可以通过向CustomersSqlDataSource设置delete命令,添加删除参数,然后执行delete命令来轻松完成此操作。

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

但请注意,这将删除数据库中的数据。

答案 3 :(得分:2)

最简单的方法是使用ASP中的某些数据源创建GridView,并在Row_Deletinng Event中调用该数据源。例如,如果您将SqlDataSource1作为GridView数据源,则Row_Deleting事件将为:

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

答案 4 :(得分:1)

请参阅以下代码并进行一些更改以获得问题的答案

<%@ 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>

答案 5 :(得分:1)

在网格中使用此代码将ID作为主要元素,以便唯一标识每个ROW

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

并搜索uique ID使用后面的C#代码中的代码(基本上这是搜索隐藏字段并将其存储在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();

    }

答案 6 :(得分:1)

解决方案有点简单;一旦从datagrid中删除了行(您的代码只从网格中删除行而不是数据源),那么您不需要执行任何其他操作。 当您在不更新数据源之后立即执行数据绑定操作时,您将从源中重新添加所有行到gridview控件(包括在前一个语句中从网格中删除的行)。

要简单地从没有数据源的网格中删除,只需在网格上调用删除操作,这就是你需要做的所有事情......之后不需要数据绑定。

答案 7 :(得分:1)

尝试此操作确保您提到的Datakeyname只是设计器文件中的列名(id)

//您的aspx代码

<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>

//您的aspx.cs代码

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
        }

答案 8 :(得分:0)

我认为你在做这个链接中提到的重新绑定错误

How to delete row from gridview?

答案 9 :(得分:0)

如果我记得以前的问题,那么你就绑定了一个DataTable。试试这个:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    DataTable sourceData = (DataTable)GridView1.DataSource;

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

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

基本上,正如我在评论中所说,抓取GridView的DataSource副本,从中删除行,然后将DataSource设置为更新的对象并再次调用DataBind()。

答案 10 :(得分:0)

这是你想要实现的诀窍。我也有像你这样的问题。

很难在RowDeleting事件中获取选定的行和数据键但是在SelectedIndexChanged事件中很容易获得选定的行和数据键。这是一个例子 -

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

答案 11 :(得分:0)

在Page load,

中添加以下行
ViewState["GetRecords"] = dt;

然后尝试这个,

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

如果仍有任何问题,请使用BindData()方法

发送代码

答案 12 :(得分:0)

     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

答案 13 :(得分:0)

我知道这是一个迟到的答案,但它仍然可以帮助需要解决方案的人。 我建议使用OnRowCommand进行删除操作以及DataKeyNames,保留OnRowDeleting函数以避免异常。

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

在gridView中包含DataKeyNames =“ID”,并在链接按钮中指定相同内容。

<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
}

如果这有用,请给我+

答案 14 :(得分:0)

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

答案 15 :(得分:0)

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

}