从CheckBox列表中删除项目

3

这是主表单:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CheckDelete.aspx.cs"  Inherits="CheckDelete" %>

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

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
  <title></title>
 </head>
<body>
<form id="form1" runat="server">
<asp:CheckBoxList ID="chkItems" runat="server" style="width: 37px">
    <asp:ListItem Value="A"></asp:ListItem>
    <asp:ListItem Value="B"></asp:ListItem>
    <asp:ListItem Value="C"></asp:ListItem>
    <asp:ListItem Value="D"></asp:ListItem>
    <asp:ListItem Value="E"></asp:ListItem>
    <asp:ListItem Value="F"></asp:ListItem>
    <asp:ListItem Value="H"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Delete" />
<br />
<br />
</form>

表单中的代码:

protected void Button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < chkItems.Items.Count; i++)
    {
        if (chkItems.Items[i].Selected == true)
        {
           chkItems.Items.RemoveAt(i);
        }
    }

}

在我的表单中,我希望删除用户选择的项目。然而,如果我选择了3个项目,在用户点击删除后至少还会保留一个项目。我错过了什么?

3个回答

4

您需要列出想要删除的所有项目,然后逐个删除。

例如:

List<ListItem> toBeRemoved = new List<ListItem>();
for(int i=0; i<chkItems.Items.Count; i++){
    if(chkItems.Items[i].Selected == true)
        toBeRemoved.Add(chkItems.Items[i]);
}

for(int i=0; i<toBeRemoved.Count; i++){
    chkItems.Items.Remove(toBeRemoved[i]);
}

在你的例子中,你在遍历过程中移除了一些项,这将改变剩余项的索引,这会导致你在遍历时“丢失”某些项。我想这就是你问题的原因。

这很好,但如果我想清除 CheckBoxList 并使其为空怎么办? - Si8

3

尝试反向循环,例如:

protected void Button1_Click(object sender, EventArgs e)
{
    for (int i = chkItems.Items.Count -1 ; i >= 0; i--)
    {
        if (chkItems.Items[i].Selected == true)
        {
           chkItems.Items.RemoveAt(i);
        }
    }

}

1
你可以这样做。
> for (int i = 0; i < chkItems.Items.Count; i++)
    {
        if (chkItems.Items[i].Selected == true)
        {
           ListItem li =new ListItem();
           li.Text = chkItems.Items[i].Text;  
           li.Value = chkItems.Items[i].Value;  
           chkItems.Items.Remove(li);
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接