I'm trying to remove empty items in listbox in C#
So i want to remove empty items in listbox like whitespace so Far I have this code. But the compiler is giving me an error
for (int i = 0; i < listBox2.Items.Count; i++)
{
if (listBox2.Items[i].ToString = " "){//ERROR*
listBox2.Items.RemoveAt(i);
}
}
*Cannot convert method group 'ToString' to non-delegate type 'bool'. Did you int开发者_C百科end to invoke the method?
ToString
is a method, so you need it to be ToString()
, and equality comparisons are performed with two equals signs ==
, not one. One equals sign is for assignment.
With that said, to iterate over your collection and remove items by their index, you'll want to go in reverse. You'll notice that as you remove items, your item count will obviously drop, so your loop will not behave like you think it will. So go for something like this:
int count = listBox2.Items.Count;
for (int i = count - 1; i >= 0; i--)
{
if (listBox2.Items[i].ToString() == " ")
{
listBox2.Items.RemoveAt(i);
}
}
Try
if (String.IsNullOrWhiteSpace(listBox2.Items[i].ToString())){
However! Since you're removing items, that means that the enumerator won't work properly. If your list box items are
- "a"
- " "
- "b"
Then your code will:
- Keep a. (Index 0)
- Remove " ". (Index 1, "b" becomes the new index 1)
- Throw an
IndexOutOfRangeException
. (Because there is not item 2)
Instead, try
List<int> itemsToRemove = new List<int>(); // using System.Collections.Generic
for (int i = 0; i <= listBox2.Items.Count; i++)
{
if (String.IsNullOrWhiteSpace(listBox2.Items[i].ToString())){
itemsToRemove.Append(i);
}
}
foreach (int i in itemsToRemove){
listBox2.Items.RemoveAt(i);
}
It looks like you're a VB-guy. In C-based languages (like C#) there's (unlike in VB) two different operators for assigning stuff and checking stuff (I don't know the real terms). For checking if two things are equal, you use a double = (==). So what you're doing in your if statement, is assigning " " to the listbox item. This obviously doesn't return a boolean (which is what if needs). In pre-c# languages, this could cause really hard-to-find bugs, because there was no warning.
In VB, you can call a method without using parentheses. In c#, they are always needed. The compiler will think you want to store the address of the method in a delegate if you leave them out (like using AddressOf in VB.Net). When you make those two changes (and, indeed, loop backwards like Anthony Pegram said), all will work fine.
You should try this
> for (int i = 0; i <= listBox2.Items.Count; i++)
> {
> if (listBox2.Items[i].ToString() == "") //Remove ' ' space
> listBox2.Items.RemoveAt(i);
> }
> }
精彩评论