2013-03-24 145 views
3

下面是主要形式有:刪除項目從複選框列表

<%@ 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個項目,用戶在刪除後至少會有一個項目保留在表單中。我錯過了什麼?

回答

4

您需要列出所有要移除的項目,然後逐個移除它們。

例如

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

在您的示例中,您隨時移除項目,這將更改尚未循環的剩餘項目的索引。當你循環時,這會導致你「遺漏」物品。我想這是你的問題的原因。

+0

謝謝。你真棒。 – 2013-03-24 14:40:26

3

嘗試向後循環,例如,

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

} 
1

你可以這樣做。

> 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