I wanted to use Databinding on a Combobox in Winforms, like I did with Objects or a Dataset on Master-Detail relations.
Databinding with the Designer is just so easy :-)
Figure: Designer properties on the combobox
I have 2 Bindingsources, the Master-Bindingsource and the the Detail-Bindingsource.
I choose the Combobox and set the different properties (DataSource, ValueMember, DisplayMember)
- I set the ValueMember to the primary key of the Detail-Bindingsource and
- I set the SelectedValue (Databindings) to the Master-Bindingsource.Doctor (= Entity class)
Figure: Combobox properties in Designer
Problem on runtime
I get the following error
Invalid cast from System.Int32 to ClientName.Business.Entities.Doctors
Reason: The Primary key (Int32) doesn’t fit into the Entity property of the Master-Table (entity)
The problem is: the Entity Framework hides the foreign-key from me (DoctorsId).
I cannot bind to it in the Designer!
How to solve that?
Solution
Don’t use Databinding.
There is no easy way of converting a primary key (Int32) to the actual Entity, with that Integer.
So, do it manually! (AAAAAARRRRRRRGGGGGHHHHHH)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { //HACK: AARRRGHHH: Why I have todo this manually?? // With other Objects or Datasets we can do this in Designer Doctors preferredDoctor = comboBox1.SelectedValue as Doctors; if (preferredDoctor != null) { if (CurrentPatientFromBindingSource != null) { CurrentPatientFromBindingSource.Doctor = preferredDoctor; } } }
private void LoadDoctors() { doctorsBindingSource.DataSource = patientsBL.GetDoctors(); //HACK: Arrggghhh: Why do I have todo this manually? comboBox1.SelectedItem = CurrentPatientFromBindingSource.Doctors; }
Todo: Investigate if Linq to Entites provides a flag to configure: Show Foreign Key property for entity
2 comments:
You need to set SelectedItem, not SelectedValue :)
I am pretty sure, that I tried that. But I will give it another try and let you know.
THX Anonymous
Post a Comment