Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Winforms Combobox with Label and Value?

I am mostly an ASP.NET developer but I am working on a WinForms app and noticed a large difference between the ASP.NET combobox (html select) and that of WinForms. I found (maybe incorrectly so) that WinForm's combobox only has a "label" whereas ASP.NET allows you to specify a "label" and a "value".

I am looking to use a WinForms combobox (or another comparable control) with a label and a value (Foobar / 42329). Is this possible? I have attempted to search for the answer but haven't come up with much. If there is no way to accomplish that, how does one go ahead and design a WinForm combobox that would represent say Cities with their associated database id?

  • Toronto / 2324
  • Montreal / 64547
  • Vancouver / 1213
like image 654
nokturnal Avatar asked Jan 07 '10 20:01

nokturnal


People also ask

How do you use a ComboBox in WinForms?

Select New Project->Visual C#->Windows Forms App (. NET Framework), give your project a name and click OK. This action creates a WinForms project with a default form and you should see the Windows designer. Let's add a ComboBox control to the form by dragging it from Toolbox and dropping it to the form.

What method should you use to get the value of a ComboBox?

You can get selected value by using combobox1. SelectedValue and convert it to int and pass it to method.

Which method is used to add the items in a ComboBox * Items insert (); items add (); items set (); items append ();?

// Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); Step 2: After creating ComboBox, add the elements in the ComboBox. Step 3: And last add this combobox control to form using Add() method.


2 Answers

I can think of a few ways:

  • override the ToString() of a City class to return Name + " / " + Id;
  • ditto, but with a TypeConverter
  • add a DisplayText property that return the same, and use DisplayMember
  • build a shim class for the data

For the last:

var data = cities.Select(city => new {      Id = city.Id, Text = city.Name + " / " + city.Id }).ToList(); cbo.ValueMember = "Id"; cbo.DisplayMember = "Text"; cbo.DataSource = data; 
like image 97
Marc Gravell Avatar answered Oct 17 '22 12:10

Marc Gravell


Assuming that your values are unique, you can first populate a dictionary then bind the combobox to the dictionary. Unfortunately databinding requires an IList or an IListSource so you have to wrap it in Binding Source. I found the solution here.

    private void PopulateComboBox()     {         var dict = new Dictionary<int, string>();         dict.Add(2324, "Toronto");         dict.Add(64547, "Vancouver");         dict.Add(42329, "Foobar");          comboBox1.DataSource = new BindingSource(dict, null);         comboBox1.DisplayMember = "Value";         comboBox1.ValueMember = "Key";     } 
like image 40
Jamie Ide Avatar answered Oct 17 '22 11:10

Jamie Ide