【问题标题】:How to delete multiple rows in a gridview using a checkbox?如何使用复选框删除gridview中的多行?
【发布时间】:2015-08-21 20:58:13
【问题描述】:

我有一个带有复选框的 gridview,我正在尝试使用以下代码进行多次删除:

    protected void deleteUsers(object sender, EventArgs e) //deleting the selected users
{
    foreach (GridViewRow row in clientGrid.Rows) 
    {
        CheckBox selectBox = (CheckBox)row.FindControl("deleteUser");

        if (selectBox != null && selectBox.Checked) 
        {
            string bank, customerId, tMain, tSub;

            bank = bankName.InnerText;
            tMain = bank + "_main";
            tSub = bank + "_sub";

            customerId = Convert.ToString(clientGrid.DataKeys[row.RowIndex].Value);

            deleteSelected(tMain, tSub, customerId).ExecuteNonQuery();

            clientGrid.DataSource = getAllClients();
            clientGrid.DataBind();
        }
    }
}

这里是sqlCommand:

    protected SqlCommand deleteSelected (string Tmain, string Tsub, string customerId) //the sql command for deleting
{
    string connection, commandSyntax;
    connection = ConfigurationManager.ConnectionStrings["localsqlserver"].ConnectionString;
    commandSyntax = "DELETE FROM [" + Tmain + "] FROM [" + Tsub + "] t1 " + 
                        "LEFT JOIN [" + Tmain + "] t2 ON t1.customer_id = t2.customer_id " +
                            "WHERE t1.customer_id = @customer_id" ;

    SqlConnection conn = new SqlConnection(connection);
    SqlCommand cmd = new SqlCommand(commandSyntax, conn);
    cmd.Parameters.AddWithValue("@customer_id", customerId);


    conn.Open();

    return cmd;
}

这在删除唯一一个选中的用户时效果很好,但如果我选中多个,我会收到此错误:

索引超出范围。必须为非负数且小于集合的大小。
参数名称:索引

我将 gridview 数据键设置为包含 guid 的 customer_id 列。

我用的是asp.net 4.0,有什么问题?

【问题讨论】:

    标签: asp.net gridview checkbox sql-delete


    【解决方案1】:

    您遇到这种情况是因为您在 foreach 循环内重新绑定数据网格,导致您当前迭代的集合的大小发生变化,这反过来又会导致您的索引失效。

    请尝试等到您执行完所有删除操作后再重新绑定您的数据网格。

    【讨论】:

      【解决方案2】:

      为 GridView 设置 DataKeyNames:

      <asp:GridView ID="GridView1" runat="server" DataKeyNames="customer_id"></asp:GridView>

      【讨论】:

        猜你喜欢
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多