从复选框列表中删除项目

本文关键字:删除项目 列表 复选框 | 更新日期: 2023-09-27 18:05:50

主要形式如下:

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

Code in 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个项目,那么在用户点击删除之后,表单上至少会保留一个项目。我错过了什么?

从复选框列表中删除项目

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

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

在您的示例中,您删除了项目,这将改变您尚未循环遍历的剩余项目的索引。这将导致你在循环过程中"丢失"项目。我想这就是你的问题所在。

尝试向后循环,例如

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

你可以这样做。

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