ComboBox SelectedValue始终为null,无法设置

时间:2014-01-09 22:18:41

标签: c# combobox selectedvalue

我正在开发一个C#.Net 4.0 Winforms应用程序,并且在两个组合框总是为其NULL属性返回SelectedValue时遇到了一些困难。

我在此表单上有三个组合。第一个组合数据绑定到BindingSoucce,而BindingSoucce又有一个类型化的DataTable作为其DataSource。该组合按预期工作。

其他两个组合绑定到本地通用DataTables。这些是失败的。 令人不快的组合是cmbDays和cmbYears。他们的数据表通过简单的循环填充在代码中。两个表都包含人口调用结束时的数据。 dtDaysLU包含字符串列'Day'。 dtYearsLU包含字符串列'Year'。非常简单。

绑定BindingSources和combos的代码如下所示:

private void databindPermitDateCombos() 
{
    this.cmbMonth.DataBindings.Clear();
    this.cmbDay.DataBindings.Clear();
    this.cmbYear.DataBindings.Clear();

    this._bsMonthsLU.DataSource = null;
    this._bsDaysLU.DataSource = null;
    this._bsYearsLU.DataSource = null;

    this._manipulator.DataBindBindingSource(this._bsMonthsLU, this._ds.tblMonthsLU);
    this._manipulator.DataBindBindingSource(this._bsDaysLU, this._dtDays);
    this._manipulator.DataBindBindingSource(this._bsYearsLU, this._dtYears);

    this._manipulator.DataBindComboBox(this.cmbMonth, this._bsMonthsLU, "Month", "MonthNumber");
    this._manipulator.DataBindComboBox(this.cmbDay, this._bsDaysLU, "Day", "Day");
    this._manipulator.DataBindComboBox(this.cmbYear, this._bsYearsLU, "Year", "Year");
}

...其中_manipulator.DataBindComboBox如下所示:

public void DataBindComboBox(ComboBox combo, BindingSource bindingSource, string displayMemberName, string valueMemberName)
{
    combo.DataBindings.Clear();
    combo.DisplayMember = displayMemberName;
    combo.ValueMember = valueMemberName;
    combo.DataSource = bindingSource;
}

你可以看到这些都不是火箭科学。我确实想指出组合框属性的设置顺序 - 根据MSDN建议:

  • 展示会员
  • 超值会员
  • 数据源

在代码中,我试图像这样设置这些组合的SelectedValue:

this.cmbMonth.SelectedValue = this._permitMonthNum;
this.cmbDay.SelectedValue = this._permitDay.ToString();
this.cmbYear.SelectedValue = this._permitYear.ToString();

请注意,我对成员数据执行.ToString(),因为我设置了这两个组合的SelectedValue,因为填充其基础表的代码使用字符串类型:

this._dtDays.Columns.Add("Day", typeof(string));

所以我知道这不是数据类型不匹配。

调试显示.SelectedValuecmbDay组合的cmbYear属性为null。

1 个答案:

答案 0 :(得分:0)

好的@LarsTech - 你走的是正确的道路。似乎这个逻辑分支绕过了填充我的数据表的功能。所以,是的 - 我的名单中没有任何内容可供选择。

非常感谢新鲜的眼睛。我非常担心这些表中有来自之前通话的数据,我没有想到要验证。

谢谢!

库尔特