How to iterate over a combobox's items?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Say cbRoadwayType is my combobox:

for (int i = 0; i < cbRoadwayType.Items.Count; i++)
{
cbRoadwayType.SelectedIndex = i;
int val = (int)cbRoadwayType.SelectedItem // INVALID EXCEPTION cast

if (val != FILTER_ALL && val != FILTER_NOT_SET)
{
roadwayList.Add(val);
}
}

But, I get an invalid exception cast. How do I just get the value of the
combobox item, based on an index?!
 
Oops, sorry, my original code was:

for (int i = 0; i < cbRoadwayType.Items.Count; i++)
{
int val = (int)cbRoadwayType.Items;

if (val != FILTER_ALL && val != FILTER_NOT_SET)
{
roadwayList.Add(val);
}
}
 
Quimbly said:
for (int i = 0; i < cbRoadwayType.Items.Count; i++)
{
int val = (int)cbRoadwayType.Items;

if (val != FILTER_ALL && val != FILTER_NOT_SET)
{
roadwayList.Add(val);
}
}


We dont know what type is in your combobox. What did you add?

Furthermore, you should use a foreach instead of a normal for loop in
this situation.

--
Chad Z. Hower
Microsoft Regional Director
"Programming is an art form that fights back"
http://www.KudzuWorld.com/
Need a professional technical speaker at your event?
http://www.woo-hoo.net
 
maby you must use foreach

foreach(object o in combo.items)
{
try
{
int i = (int)o;
.... somes codes
}
catch
{
Console.WritLine("error with object type " + o.GetType().ToString())
}
}

Quimbly a écrit :
 
maby you must use foreach

It should work either way. I suspect the OP didn't store ints in the
combobox to start with. That's why he gets the invalid cast error
 
The problem appears to be that the ComboBox.Items property doesn't expose
the values in the list, but instead a DataRowView obj, which doesn't cast
well to an int! There must be a way to easily iterate over items in a
combobox, no?!

If the items are DataRowViews, you can't typecast them directly to ints. Can
you show the code you use to fill the combobox?
 
Sounds like you're binding directly to the dataset, which means you need one
more level of indirection. Try this:
foreach (DataRowView item in cbRoadwayType.Items) {
Int32 val = (Int32) item["ValueColumnName"];
...
}
 
Back
Top