C#ComboBox SelectedValue在焦点丢失时重置

时间:2012-01-20 11:24:56

标签: c# winforms binding combobox

C#,VS2010。

private void FillCombo()
{
    var data = from c in _ctx.Categories
                select c;
    categoryBindingSource.DataSource = data.ToList();
    cbxCategory.DataSource = categoryBindingSource;
    cbxCategory.DisplayMember = "Name";
    cbxCategory.ValueMember = "CategoryId";
    if (_dbOperation == Helper.DbOperation.Insert)
    {
        cbxCategory.SelectedIndex = -1;
    }
}

cbxCategory.DataBindings.Add("SelectedValue", bindingSource, "CategoryId");

当我从组合框中选择一个项目时,当组合框失去焦点时它会被重置。 为什么?解决方案是什么? NB。已连接到Product表。 感谢。

3 个答案:

答案 0 :(得分:2)

检查_dbOperation == Helper.DbOperation.Insert

的条件值

我猜这个条件令人满意,并且每次调用此方法后组合框都会重置为初始值。

答案 1 :(得分:0)

请检入UIForm.Designer.cs文件,如果您使用它,可能是您没有注意到双DataBinding行,请查找类似的行:

// Master->Details ::= Category->Products

//
// categoryIdComboBox
//

// 1.
// this.categoryIdComboBox.DataBindings.Add("SelectedValue", this.productBindingSource, "CategoryId", true);
// 2.
this.categoryIdComboBox.DataBindings.Add("SelectedItem", this.productBindingSource, "Category", true);
// 3.
// this.categoryIdComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.productBindingSource, "CategoryId", true));
// 4.
// this.categoryIdComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.productBindingSource, "Category", true));

起初我有3和4行没有注释,并且有像你一样的问题。 当我只离开1行时,它没有注释,它已经唤醒,但我在验证方面遇到了问题。

我的解决方案是仅取消注释2. line。

也许它只适用于4.行。

答案 2 :(得分:0)

对于winforms以这种方式绑定它(对于强类型)

comboBoxFollowedBy.DataBindings.Add("SelectedValue", bindingSource1, "FieldName", true, DataSourceUpdateMode.OnPropertyChanged);