简体   繁体   English

使用组合框的最佳方法(同时显示文本和数据库文本)

[英]Best way to use Combobox (Bind display text and database text together)

I am creating a new window called AMTI which is using comboboxes to display different selections for the user. 我正在创建一个名为AMTI的新窗口,该窗口正在使用组合框为用户显示不同的选择。 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. 选择文本可以例如是“分析的”,在这种情况下,值“ E04”应存储在数据库中AMTI表的适当列中。 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? 在组合框中将显示文本与要存储在数据库中的值进行映射的最简单(或正确)方法是什么?

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. 您可以将ComboBox绑定到元素公开了公共属性(包括数据表)的任何集合,或者,如果您还没有准备好集合并且需要键值对象,则可以使用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: 您还可以将ComboBox绑定到Linq查询结果:

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. 这些只是一些可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM