Search code examples
c#winformscomboboxkeyvaluepair

Bind List<KeyValuePair> to combobox


I cannot create a class or my own object so I thought I would use a List<KeyValuePair> to store two properties and then bind this object to a combobox.

However, I cannot see how I can set the valueField and TextField in the combobox.

The code.

List<KeyValuePair<int, string>> kvpObject = 
 new List<KeyValuePair<int, string>>();

foreach (User u in m_users) {

    kvpObject.Add(new KeyValuePair<int, string>(u.ID, u.Name));
}

// Bind Add Users combobox
cmboBox.DataSource = kvpObject;
cmboBox.ValueField = "????" // Maybe something like kvpObject[0]..
cmboBox.TextField  = "????";
cmboBox.DataBind();

Does anyone know what I need to put inside the ????.


Solution

  • I think it should be like this:

    cmboBox.ValueField = "Key";
    cmboBox.TextField  = "Value";
    

    Because you are using the KeyValuePair. The properties is Key and Value

    Update:

    I also have a suggestion. Instead of using a for loop. Then you can use Linq to bind it to the datasource of the combobox. Something like this:

    cmboBox.DataSource = m_users
                          .Select (s =>new KeyValuePair<int,string>(s.ID,s.Name))
                          .ToList();
    cmboBox.ValueField = "Key";
    cmboBox.TextField  = "Value";
    cmboBox.DataBind();
    

    Remember to include System.Linq;