删除项目从复选框列表
问题描述:
下面是主要形式有:删除项目从复选框列表
<%@ 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个项目,用户在删除后至少会有一个项目保留在表单中。我错过了什么?
答
您需要列出所有要移除的项目,然后逐个移除它们。
例如
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);
}
}
+0
谢谢!真的很有帮助。 – 2013-03-24 15:09:12
+0
@ScottAnderson因此,它投票! – Samidjo 2013-10-22 22:20:40
谢谢。你真棒。 – 2013-03-24 14:40:26