davitp
davitp

Reputation: 125

Get back information from combo box in .NET WinForms

My question is about combo boxes in WinForms. So assume we have a generic list and SingleItem class with a lot of fields. For example

class SingleItem{
    public int val1;
    public int val2;
    public string str;
    public override string ToString(){
        return str;
    }
};
List<SingleItem> listOfItems;

Assume, that we have comboBox variable. I'm adding items to comboBox this way

foreach(SingleItem item in listOfItems){
    comboBox.Items.Add(item);
}

And then, when user finished choosing an item, we need to get another field from chosen item. For example, i need something like this

comboBox.SelectedItem.val1; // where val1 is field of SingleItem class

That is the problem. I tried to Google this problem, but didn't find valuable answer for my question. I also tried to do a type conversion, but it fails. My current solution is searching selected value in list, but this solution have O(n) complexity and not good enough. Thanks

Upvotes: 1

Views: 226

Answers (2)

Luc Morin
Luc Morin

Reputation: 5380

Here's how I would do this:

class SingleItem
{
    public int val1 { get; set; }
    public int val2 { get; set; }
    public string str { get; set; }
    public override string ToString()
    {
        return str;
    }

}

...

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var obj = ((SingleItem)comboBox1.SelectedItem).val1; 
}

Cheers

Upvotes: 4

thijs1095
thijs1095

Reputation: 89

Try to use an Array instead of a itemlist, Arrays are easier to add in combobox

Here is code to get the value of selected item in combobox:

string str = (string)ComoBox.SelectedItem;

Hope this helps you!

Upvotes: 0

Related Questions