Domanda

i found this class and I use it to generate items for my Combo Boxes (as a datasource):

 public class ComboBoxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

The problem is whenever I need the access the selected value of a ComboBox, it always returns the Text, Although the value and the Text are both visible when I parse my app, I can't access the Value. see the picture:

ToString()
and this pic:
Value not accessible

I guess I need a ToInt() function to return the Value of my class as an int. How can I achieve it ?

È stato utile?

Soluzione

You need to cast SelectedItem to ComboBoxItem, then access it's Value property :

var i = ((ComboBoxItem)sTD_PROVINCEComboBox.SelectedItem).Value;

With that i will contain the Value, so in the foreach you can simply do as follow :

foreach(var item in UE2.Cities.Where(x => x.CITY_PROVINCE_ID == i)

UPDATE :

Just notice that Value property of ComboBoxItem is of type object (I was assuming it is int). If this is the case, the above foreach part won't compile (comparing int with object is not allowed). Assuming CITY_PROVINCE_ID is of type int, and i storing boxed int you'll need to unbox i back to int :

foreach(var item in UE2.Cities.Where(x => x.CITY_PROVINCE_ID == (int)i)

Altri suggerimenti

To access the Value property, you need to cast the SelectedItem to the right type:

object i = ((ComboBoxItem)sTD_PROVINCEComboBox.SelectedItem).Value;

Note that i is of type object. I suppose that the CITY_PROVINCE_ID is of type int. You can not test for reference equality of an object and an int, so a statement like this does not even compile:

foreach(var item in UE2.Cities.Where(x => x.CITY_PROVINCE_ID == i) 

The error message will be something along the lines of "Operator '==' cannot be applied to operands of type 'object' and 'int'".

What you can do instead is cast the object back to an int:

object o = ((ComboBoxItem)sTD_PROVINCEComboBox.SelectedItem).Value;
int i = (int)o; 

This will obviously only work if you're only ever storing ints as values. If Value might contain something else (say, a string), you need to test against that as well;

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top