从复选框列表中删除项目 [英] Remove Items From a CheckBox List

查看:47
本文介绍了从复选框列表中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是主要形式:

<%@ 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个项目,则在用户单击Delete后至少有一项将保留在表单上.我想念什么?

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. 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.

例如

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.

这篇关于从复选框列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆