4

Using C# Entity Framework objects like below 2

item:

  • itemname
  • itemtypeid
  • itemprice
  • itemsize

itemtype:

  • typeid
  • typename
  • currentprice
  • typesize

On item edit form there is a combobox called typeidComboBox bound to item.itemtypeid and item list datasource loading from itemtype datasource.

When Form Loads Binding Sources will set like.

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

The problem raise when I add some code like below in SelectionChangeCommitted event.

Code:

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

Why Combobox selection cancelling and backing to old value when SelectionChangeCommitted event handled like Combobox's BindingSource property changed in it?

Sorry my English.

Namchin
  • 61
  • 4

1 Answers1

2

I don't know why. But it solved my problem: DataBinding.WriteValue and ComboBox.SelectedItem.

Here is my working code.

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;
}
Namchin
  • 61
  • 4