I have a listbox being populated from a SQLDATA pull, and it pulls down some columns that i dont want like OBJECT_dfj, OBJECT_daskd. The key is all of these being with OBJE
You want to iterate backwards through using a counter instead of foreach. If you iterate forwards you have to adjust the counter as you delete items.
for(int i=listBox1.Items.Count - 1; i > -1; i--) {
{
if(listBox1.Items[i].Contains("OBJECT"))
{
listBox1.Items.RemoveAt(i);
}
}
You can try this also, if you don't want to deal with the enumerator:
object ItemToDelete = null;
foreach (object lsbItem in listbox1.Items)
{
if (lsbItem.ToString() == "-ITEM-")
{
ItemToDelete = lsbItem;
}
}
if (ItemToDelete != null)
listbox1.Items.Remove(ItemToDelete);
I found out the hard way that if your listbox items are assigned via a data source
List<String> workTables = hhsdbutils.GetWorkTableNames();
listBoxWork.DataSource = workTables;
...you have to unbind that before doing the removal:
listBoxWork.DataSource = null;
for (int i = listBoxWork.Items.Count - 1; i >= 0; --i)
{
if (listBoxWork.Items[i].ToString().Contains(listboxVal))
{
listBoxWork.Items.RemoveAt(i);
}
}
Without the "listBoxWork.DataSource = null;
" line, I was getting, "Value does not fall within the expected range"
The problem here is that you're changing your enumerator as you remove items from the list. This isn't valid with a 'foreach' loop. But just about any other type of loop will be OK.
So you could try something like this:
for(int i=0; i < listBox1.Items.Count; )
{
string removelistitem = "OBJECT";
if(listBox1.Items[i].Contains(removelistitem))
listBox1.Items.Remove(item);
else
++i;
}