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
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (textBox1.Text == listBox1.Items[i].ToString())
{
jeElement = true;
break;
}
}
if (jeElement)
{
label1.Text = "je element";
}
else
{
label1.Text = "ni element";
}
textBox1.ResetText();
textBox1.Focus();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt == true && e.KeyCode == Keys.A)
{
buttonCheck.PerformClick();
}
}
}
You can use following code too:
foreach (var item in listBox1.Items.Cast<string>().ToList())
{
string removelistitem = "OBJECT";
if (item.Contains(removelistitem))
{
listBox1.Items.Remove(item);
}
}
protected void lbAddtoDestination_Click(object sender, EventArgs e)
{
AddRemoveItemsListBox(lstSourceSkills, lstDestinationSkills);
}
protected void lbRemovefromDestination_Click(object sender, EventArgs e)
{
AddRemoveItemsListBox(lstDestinationSkills, lstSourceSkills);
}
private void AddRemoveItemsListBox(ListBox source, ListBox destination)
{
List<ListItem> toBeRemoved = new List<ListItem>();
foreach (ListItem item in source.Items)
{
if (item.Selected)
{
toBeRemoved.Add(item);
destination.Items.Add(item);
}
}
foreach (ListItem item in toBeRemoved) source.Items.Remove(item);
}
You can't modify the references in an enumerator whilst you enumerate over it; you must keep track of the ones to remove then remove them.
This is an example of the work around:
List<string> listbox = new List<string>();
List<object> toRemove = new List<object>();
foreach (string item in listbox)
{
string removelistitem = "OBJECT";
if (item.Contains(removelistitem))
{
toRemove.Add(item);
}
}
foreach (string item in toRemove)
{
listbox.Remove(item);
}
But if you're using c#3.5, you could say something like this.
listbox.Items = listbox.Items.Select(n => !n.Contains("OBJECT"));
You can do it in 1 line, by using Linq
listBox1.Cast<ListItem>().Where(p=>p.Text.Contains("OBJECT")).ToList().ForEach(listBox1.Items.Remove);
You could try this method:
List<string> temp = new List<string>();
foreach (string item in listBox1.Items)
{
string removelistitem = "OBJECT";
if(item.Contains(removelistitem))
{
temp.Items.Add(item);
}
}
foreach(string item in temp)
{
listBox1.Items.Remove(item);
}
This should be correct as it simply copies the contents to a temporary list which is then used to delete it from the ListBox.
Everyone else please feel free to mention corrections as i'm not 100% sure it's completely correct, i used it a long time ago.