4

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 ????.

Jørgen R
  • 10,568
  • 7
  • 42
  • 59
user3428422
  • 4,300
  • 12
  • 55
  • 119

1 Answers1

14

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;

Arion
  • 31,011
  • 10
  • 70
  • 88