Skip to main content
 首页 » 编程设计

c#之ComboBox 和 KeyValuePair 列表无法正常工作

2024年02月20日12bluestorm

我在 Windows Forms 上创建了一个组合框形式。它数据绑定(bind)到 TableAdapter 中的列,数据源是手动创建的 KeyValuePair 列表。问题是当表格显示时; ValueMember 显示在 ComboBox 中,而不是 DisplayMember。如果单击下拉列表,将显示键列表值。当您进行选择时,在 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中的Column是int,而List中的Value是string,就会出现上面的问题。我将数据绑定(bind)更改为一个 View ,该 View 显示 int 绑定(bind)到的查找表中的文本。列表的键是查找表中的 int。如果这有意义的话。

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

然后 KeyValuePair 按预期工作。

请您参考如下方法:

我将一个带有 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); 
    } 

验证处理程序有正确的选择项并且它初始化得很好。可能是您没有在代码片段中显示的其他内容。