简体   繁体   English

从CheckBox列表中删除项目

[英]Remove Items From a CheckBox List

Here is main form: 这是主要形式:

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

}

In my form, I want to delete the items that the user has checked off. 在我的表单中,我想删除用户已签出的项目。 However, if I select 3 items, at least one item will remain on the form after the user hits delete. 但是,如果我选择3个项目,则在用户点击删除后,表单上将至少保留一个项目。 What am I missing? 我错过了什么?

You'll need to make a list of all the items you want to remove and then remove them one by one. 您需要列出要删除的所有项目,然后逐个删除它们。

eg 例如

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

In your example, you remove the items as you go which will change the index of the remaining items that you've yet to loop through. 在您的示例中,您将删除项目,这将更改您尚未循环的其余项目的索引。 This will result with you "missing" items as you loop through. 这将导致您在循环时“丢失”项目。 I imagine that's the cause of your problem. 我想这就是问题的原因。

Try looping backwards, eg 尝试向后循环,例如

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

}

You can do like this. 你可以这样做。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM