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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With