Scott Anderson
Scott Anderson

Reputation: 33

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. What am I missing?

Upvotes: 3

Views: 16247

Answers (3)

Ashfaq Shaikh
Ashfaq Shaikh

Reputation: 1668

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

Upvotes: 1

Netricity
Netricity

Reputation: 2738

Try looping backwards, e.g.

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

}

Upvotes: 3

Grant Clements
Grant Clements

Reputation: 984

You'll need to make a list of all the items you want to remove and then remove them one by one.

e.g.

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.

Upvotes: 4

Related Questions