コンボボックスを使用してユーザーにさまざまな選択肢を表示する AMTI という新しいウィンドウを作成しています。選択テキストは、たとえば「分析」である可能性があります。この場合、値「E04」は、データベースの AMTI テーブルの適切な列に格納する必要があります。databinding に列挙型を使用することについて読みましたが、ここではテキストと数値が結び付けられており、コンボボックスでデータバインドできます。コンボボックスの表示テキストをデータベースに格納する値にマッピングするための最も簡単な (または正しい) 方法は何ですか?
1390 次
1 に答える
1
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;
... またはバインディング用のオブジェクトの独自のクラスを作成します。
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;
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";
これらは可能性のほんの一部です。
于 2013-09-12T11:12:07.357 に答える