如何使用复选框删除gridview中的多行?

时间:2012-03-25 18:13:30

标签: asp.net gridview checkbox sql-delete

我有一个带有复选框的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;
}

这对删除唯一一个已检查用户很有效但如果我检查多个我收到此错误:

  

指数超出范围。必须是非负数且小于集合的大小。
  参数名称:index

我将gridview datakey设置为包含guid的customer_id列。

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

2 个答案:

答案 0 :(得分:0)

您遇到这种情况是因为您在foreach循环中重新绑定数据网格,导致当前迭代的集合更改大小,这反过来又会导致索引关闭。

请尝试等待,直到执行了所有删除后重新绑定数据网格。

答案 1 :(得分:0)

为GridView设置DataKeyNames:

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