1

I have created a ComboBox on a Windows Forms form. It is Databound to a column in a TableAdapter and the DataSource is a manually created KeyValuePair List. The problem is that when the form is displayed; the ValueMember is displayed in the ComboBox, not the DisplayMember. If you click the drop down, the Key List Values are displayed. When you make a selection, in the OnValidating method, the SelectedItem is -1.

I believe that the ComboBox is setup correctly. What have I done wrong?

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";

Problem solved:

I found that if the Column in the DataBinding is an int, but the Value from the List is a string, then the problem above resulted. I changed the Databinding to a view that displayed the text from the lookup table the int tied to. The Key of the List would be the int from the lookup table. If that makes any sense.

SELECT DisplayMember FROM LookupTable AS LT INNER JOIN DataTable AS DT ON LT.Id = DT.LookupId.

Then the KeyValuePair worked as expected.

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

你为什么使用 aList<KeyValuePair<int,string>>而不是 a Dictionary<int,string>

无论如何,我确实相信您的问题在于,由于绑定是针对 KeyValuePair 列表完成的;代码会认为它应该在 List 中查找 DisplayMember 的值(即,不是 KeyValuePair)并发现 Value 是 KeyValue 并且没有找到任何 Key,因此它会进行一些奇怪的解析(阅读:不确定关于为什么你得到-1)。认为从List<KeyValuePair<int,string>>字典切换可能会解决它。

于 2012-08-16T14:04:00.790 回答