winforms – C#Windows窗体ComboBox的SelectionChangeCommitted事件防止在Combobox的BindingSource属性发生变化时选择更改

使用C#Entity Framework对象,如下所示2

项目:

> itemname
> itemtypeid
> itemprice
> itemsize

物品种类:

> typeid
> typename
> currentprice
> typesize

在项目编辑表单上有一个名为typeidComboBox的组合框绑定到item.itemtypeid,项目列表数据源从itemtype datasource加载.

当Form Loads绑定源将设置为.

    private void Form1_Load(object sender, EventArgs e)
    {
        db = new dbtestEntities();
        itemtypeBindingSource.DataSource = db.usertypes;
        itemBindingSource.DataSource = db.users;

        typeidComboBox.DataBindings.Clear();
        typeidComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.itemBindingSource, "itemtypeid", true));
        typeidComboBox.DataSource = this.itemtypeBindingSource;
        typeidComboBox.DisplayMember = "typename";
        typeidComboBox.ValueMember = "typeid";
        typeidComboBox.SelectionChangeCommitted += typeidComboBox_SelectionChangeCommitted;
    }

当我在SelectionChangeCommitted事件中添加如下代码时,问题就出现了.

码:

private void typeidComboBox_SelectionChangeCommitted(object sender, EventArgs e)
    {
        (itemBindingSource.Current as item).itemprice = (itemtypeBindingSource.Current as itemtype).currentprice;
    }

为什么Combobox选择取消并支持在处理类似Combobox的BindingSource属性的SelectionChangeCommitted事件时更改旧值?

对不起我的英文.

最佳答案 我不知道为什么.但它解决了我的问题:DataBinding.WriteValue和ComboBox.SelectedItem.

这是我的工作代码.

private void typeidComboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
    foreach (Binding binding in (sender as ComboBox).DataBindings)
        {
            binding.WriteValue();
        }
    (itemBindingSource.Current as item).itemprice = ((sender as ComboBox).SelectedItem as itemtype).currentprice;
}
点赞