簡體   English   中英

從CheckBox列表中刪除項目

[英]Remove Items From a CheckBox List

這是主要形式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM