0

I am creating a new window called AMTI which is using comboboxes to display different selections for the user. The selection text could for example be "Analytical", in which case the value "E04" should be stored in appropriate column in the AMTI-table in the database. I read about using enums for databinding, but here a text and a numeric value are tied together, which can then be databound in the combobox. What is the easiest (or correct) approach for mapping a display text in a combobox with a value to be stored in the database?

Community
  • 1
  • 1
Kasper Hansen
  • 6,307
  • 21
  • 70
  • 106

1 Answers1

1

You can bind ComboBox to any collection which elements expose public properties, including datatable, or, if you don't have a collection ready and need key-value objects, you can use Dictionary.

Dictionary<string, int> dict = new Dictionary<string, int>();

 // fill the dictionary here
 mycomboBox.DataSource = new BindingSource(dict, null);
 mycomboBox.DisplayMember = "Key";
 mycomboBox.ValueMember = "Value";

 if(mycomboBox.SelectedIndex!=-1)
    int currentlySelected = (int)mycomboBox.SelectedValue;

... or make your own class of objects for binding:

class NameValueHolder
{
   public string Name{get;set;}
   public int Value{get;set;}
   public NameValueHolder(){}//so you can use it in linq
   public NameValueHolder(string name, int value)
   {
      this.Name=name;
      this.Value=value;
   }
}

BindingList<NameValueHolder> list = new BindingList<NameValueHolder>();
list.Add(new NameValueHolder("object 1", 1);
list.Add(new NameValueHolder("object 2", 2);
list.Add(new NameValueHolder("object 3", 3);

mycomboBox.DataSource = new BindingSource(list, null);
mycomboBox.DisplayMember = "Name";
mycomboBox.ValueMember = "Value";

if(mycomboBox.SelectedIndex!=-1)
   NameValueHolder currentlySelected = (NameValueHolder)mycomboBox.SelectedValue;

You can also bind ComboBox to Linq query result:

var qResult = from a in yourDataSource
    where (/*some condition*/)
    select new {Name = a.someName, Value = a.someValue};
mycomboBox.DataSource = qResult.ToList();
mycomboBox.DisplayMember = "Name";
mycomboBox.ValueMember = "Value";

Those are just some of the posibilities.

Arie
  • 5,251
  • 2
  • 33
  • 54