1

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は期待どおりに機能しました。

4

2 に答える 2

4

ComboBoxとButtonを備えたウィンドウを一緒に投げました。あなたが何を説明しているのか全くわかりません。私のコードは次のようになります。

    BindingSource bs = new BindingSource();
    public Form1()
    {
        InitializeComponent();
        comboBox1.DataBindings.Add(new Binding("Text", bs, "Format", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
        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"));
        comboBox1.DataSource = new BindingSource(loFormat, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";
    }

    private void comboBox1_Validating(object sender, CancelEventArgs e)
    {
        Console.WriteLine(comboBox1.SelectedItem);
    }

検証ハンドラーには正しい選択された項目があり、正常に初期化されます。たぶん、それはあなたがあなたのコードスニペットに示していない何か他のものです。

于 2012-08-16T14:15:46.790 に答える
0

なぜのList<KeyValuePair<int,string>>代わりに使用しているのDictionary<int,string>ですか?

とにかく、私はあなたの問題がKeyValuePairのリストに対してバインディングが行われているという事実にあると信じています。コードは、リスト内のDisplayMemberの値(つまり、KeyValuePairではない)を検索する必要があると考え、値がKeyValueであることを検出し、キーを検出しないため、奇妙な解析を行います(読み取り:不明-1を取得する理由について)。List<KeyValuePair<int,string>>辞書に切り替えることで解決できるかもしれないと考えてください。

于 2012-08-16T14:04:00.790 に答える