tags:

views:

110

answers:

2

I pull data from a table in a database and assign it as a datasource to a listbox. If there is a blank item in the listbox, it shows up as something like this:

  1. All
  2. Red
  3. Green
  4. Blue

What is the best way to remove the blank in the listbox. If there is a blank, it is always in the second position. I was going to try to test to see if the second position contained blank text, but I am not sure how to do that.

Thanks, XaiSoft

+3  A: 

I'd say the best thing to do is to remove the blank item from your datasource before you bind it to the listbox.

How you do this depends on where your data's coming from and how much control you have over it.

You could add a view to the database that only returns non-blank items; if you're using LINQ to SQL you could modify your query so that it only returns non-blank items; you could copy the items into a List and remove the blank ones yourself (I guess there aren't too many items if you're putting them in a listbox).

teedyay
Thats the problem. I actually would do that, but unfortunately, am unable to because of restrictions.
Xaisoft
(Edited my answer to elaborate on my point a little.) What are your restrictions? How are you getting the data?
teedyay
I actually have no control over the data. The only control I have is on the listbox.
Xaisoft
Can you provide a code sample? If you're saying myListBox.DataSource = someDataSource, then you can say ArrayList myList = someDataSource; then remove the blanks from myList, then say myListBox.DataSource = myList;
teedyay
However, if you're binding in some other way, the above doesn't apply. More detail please!
teedyay
What I ended up do was just testing if the item at index 1 is equal to "", then I remove it. This works! Thanks for your help!
Xaisoft
Checking the values after you've bound is OK; it's generally tidier to clean up your data first. Don't just check item 1 though! What if the data in the database changes and now it's item 3 that's blank? Go through all the items and check each one.
teedyay
+2  A: 

Hook up an event to the data bind of the list box. If the data item is empty or has an invalid string, then do not add it, else go ahead an add it.

Or loop through the data source yourself, and add only what is needed.

David Basarab