ComboBox - Add a string to display and associated data

Hello,

How can i add some item (kind of <DisplayMember ,ValueMember >) in a combobox when the combo is not bind with a DataSet

I try to create an 'Item' class inherit from object. but i don't know how to display the string member in the combo.

Thanks and Regards. 

 



Answer this question

ComboBox - Add a string to display and associated data

  • Bill Sullivan

    Just set DisplayMember and ValueMember to the names of the properties you want to use. Like this:

    class MyListItem
    {
         private string _myDisplayMember;
         private int _myValueMember;

         public MyListItem(string displayMember, int valueMember)
         {
              _myDisplayMember = displayMember;
              _myValueMember = valueMember;
         }

         public string MyDisplayMember
         {
              get
              {
                   return _myDisplayMember;
              }
         }

         public string MyValueMember
         {
              get
              {
                   return _myValueMember;
              }
         }
    }

    Then to bind to the combo box:

    cboMyCombo.DataSource = new MyListItem[] {new MyListItem("First Item", 1), new MyListItem("Second Item", 2)};
    cboMyCombo.DisplayMember = "MyDisplayMember";
    cboMyCombo.ValueMember = "MyValueMember";



  • ComboBox - Add a string to display and associated data