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
The error you are getting means that
foreach (string item in listBox1.Items)
should be replaced with
for(int i = 0; i < listBox1.Items.Count; i++) {
string item = (string)listBox1.Items[i];
In other words, don't use a foreach.
EDIT: Added cast to string in code above
EDIT2: Since you are using RemoveAt(), remember that your index for the next iteration (variable i in the example above) should not increment (since you just deleted it).
With this code you can remove every item from your listbox ... Notice that you should write this code in the click event of your button :
if (listBox1.SelectedIndex != -1)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
You can't modify a collection while you're iterating over it with foreach. You might try using a regular for() statement.
You may need to iterate backwards from the end of the collection to make sure you cover every item in the collection and don't accidentally overrun the end of the collection after removing an item (since the length would change). I can't remember if .NET accounts for that possibility or not.
You can't use an enumerator, you have to loop using an index, starting at the last item:
for (int n = listBox1.Items.Count - 1; n >= 0; --n)
{
string removelistitem = "OBJECT";
if (listBox1.Items[n].ToString().Contains(removelistitem))
{
listBox1.Items.RemoveAt(n);
}
}
Your question implies that you're willing to modify other parts of the code, even though you can't modify the SQL Statement itself. Instead of removing them from the ListBox Collection, it might be easier to just exclude them in the first place. This code assumes you're connecting to SQL Server:
void PopulateListBox(ListBox listToPopulate)
{
SqlConnection conn = new SqlConnection("myConnectionString");
SqlCommand cmd = new SqlCommand("spMyStoredProc", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string item = reader.GetString(0); //or whatever column is displayed in the list
if (!item.Contains("OBJECT_"))
listToPopulate.Items.Add(item);
}
}
But if you're absolutely determined to do it this way you should check out this question on modifying an enumerable collection while iterating through it.
Sorry guys i had to adjust the string
sqldatapull = dr[0].ToString();
if (sqldatapull.StartsWith("OBJECT"))
{
sqldatapull = "";
}
listBox1.Items.Add(sqldatapull);
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
if (String.IsNullOrEmpty(listBox1.Items[i] as String))
listBox1.Items.RemoveAt(i);
}
}