How can i use second method instead of first?
first (web user control)
public void Remove() { int count = this.ListBox1.Items.Count; for (int i = count - 1; i > -1; i--) { if (ListBox1.Items[i].Selected) { ListBox1.Items.Remove(ListBox1.Items[i]); } } }
Test.aspx(Test of first)
protected void btnRemove_Click(object sender, EventArgs e) { ItemOrderer2.Remove(); }
second(web user control)
public void Remove(string value) { ListItem li = new ListItem(); li = ListBox1.Items.FindByValue(value); if (li != null) { this.ListBox1.Items.Remove(li); }
Test.aspx( Test of Second)
protected void btnRemove_Click(object sender, EventArgs e) { // ItemOrderer2.Remove(); if (ItemOrderer2.Items.Count > 0) foreach (ListItem li in ItemOrderer2.Items) { if (li.Selected) { ItemOrderer2.Remove(li.Value); } } }
You can’t use
foreachif you are removing data inside theforeach– it (intentionally) breaks the iterator.If
forworks, why change it? If you are desperate to useforeach, then build a separate list first – for example:The first query can often be simplified by LINQ if if is available.