WindowsフォームフォームでComboBoxを作成しました。これはTableAdapterの列にデータバインドされ、データソースは手動で作成されたKeyValuePairリストです。問題は、フォームが表示されるときです。ValueMemberは、DisplayMemberではなくComboBoxに表示されます。ドロップダウンをクリックすると、キーリスト値が表示されます。選択すると、OnValidatingメソッドでは、SelectedItemは-1になります。
ComboBoxは正しく設定されていると思います。私は何を間違えましたか?
this.cboFormat.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.BindingSource, "Format", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
InitializeComponent();
List<KeyValuePair<int, string>> loFormat = new List<KeyValuePair<int, string>>();
loFormat.Add(new KeyValuePair<int, string>(1, "Format 1"));
loFormat.Add(new KeyValuePair<int, string>(2, "Format 2"));
loFormat.Add(new KeyValuePair<int, string>(3, "Format 3"));
this.cboFormat.DataSource = new BindingSource(loFormat, null);
this.cboFormat.DisplayMember = "Value";
this.cboFormat.ValueMember = "Key";
問題が解決しました:
DataBindingの列がintであるが、リストの値が文字列である場合、上記の問題が発生することがわかりました。データバインディングを、intが関連付けられているルックアップテーブルのテキストを表示するビューに変更しました。リストのキーは、ルックアップテーブルからのintになります。それが理にかなっているなら。
SELECT DisplayMember FROM LookupTable AS LT INNER JOIN DataTable AS DT ON LT.Id = DT.LookupId.
その後、KeyValuePairは期待どおりに機能しました。