How can I save the correct ValueMember of a ComboBox to the entities/db?

549 Views Asked by At

How can I save the correct ValueMember of a ComboBox to the entities/db? My Winform has ComboBoxes that take Values from Entities of a Lookup Data tabel, as in the following code:

    private void FillComboBoxes()
    {
        chargedToComboBox.Invalidate();
        ModelCS ctx = new ModelCS();
        var query1 = from a in ctx.LuDatas
                     where a.Category == "Charged To" && a.IsActive == true
                     select new { LuValueMember = a.LuValueMember,
                                  LuDisplayMember = a.LuDisplayMember };

        var chargedTo = query1.ToList();
        chargedToComboBox.DataSource = chargedTo;
        chargedToComboBox.DisplayMember = "LuDisplayMember";   
        chargedToComboBox.ValueMember = "LuValueMember";     

        string ch = chargedToComboBox.SelectedValue.ToString();
        MessageBox.Show(ch);      // variable ch shows the CORRECT
                                  // ValueMember
        chargedToTextBox.Text = ch;     // variable ch show the UNDESIRABLE                 
                                        // DisplayMember
        this.Refresh();

    }

On SaveChanges() I get the following error: 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll

To find out what is happening, I added a TextBox to the form, and attempted to store in the what I thought was the ComboBox.ValueMember. To do this, I stored the the ComboBox.SelectedValue in a variable (ch) and and stored this variable in the TextBox.Text. What shows up in the TextBox.Text is the DisplayMember of the Combo, not the ValueMember.

To test why, I added a MessageBox to the code to see the vaslue of 'ch'; it shows the corresct value of the ValueMember.

How can it be that in the MessageBox 'ch' has one value and in the TextBox.Text it has another?

All I wanted was to extract a lookup list from the LuData entities, show the choices by name in the ComboBox and store the value by a code in the database.

1

There are 1 best solutions below

1
shadow On

Try this:

chargedToTextBox.Text = chargedToComboBox.SelectedItem.ToString();