ComboBox DataBinding 1/2 working

S

Steve K.

I've got a strange situation here with a DataBound ComboBox. When I change
the selected item from the list my DataBound object is updated. When I try
to restore the data the item in the ComboBox is not selected.

Here is the relevant code:
<code>
public void SetAvailablePlans(List<InsurancePlan> plans)
{
//comboBox_PlanType.Items.Clear();
InsurancePlan blankPlan = new InsurancePlan();
blankPlan.Name = "New";
blankPlan.InternalID = "-1";

plans.Insert(0, blankPlan);


comboBox_PlanType.SelectedIndexChanged -=
comboBox_PlanType_SelectedIndexChanged;
comboBox_PlanType.DataSource = plans;
comboBox_PlanType.DisplayMember = "Name";
comboBox_PlanType.ValueMember = "InternalID";
comboBox_PlanType.SelectedIndexChanged +=
comboBox_PlanType_SelectedIndexChanged;
}

private void BindPolicy(InsurancePolicy policy)
{
if(policy != null)
{
// other controls removed...

comboBox_PlanType.DataBindings.Add(new Binding("SelectedItem",
policy, "PlanType"));
}
}
</code>

I'm not using a BindingSource because there are some strange things that
happen when you use a BindingSource with nested UserControls.

Looking at the above code; Insurancepolicy has an InsurancePlan property
(called "PlanType"). Unless I'm really missing something, this seems to be
the correct way to set things up.

Like I said, the DataBinding is working to an extent, the item based in to
BindPolicy is updated when I change the selected item in the ComboBox, but
it won't SET the selection when it's initially bound.

Driving me nuts... hopefully someone can shed a little light on this for me.

Thanks,
Steve
 
M

Morten Wennevik [C# MVP]

Hi Steve,

It's kind of hard to tell from your sample but things to check would be the
order you bind the policy to the control. Is this done before or after you
set the ComboBox.DataSource? Try calling BindPolicy after SetAvailablePlans

Using a BindingSource you would typically do a ResetBinding() after having
set everything up to force all controls to update themselves. By the way, a
BindingSource works fine in nested usercontrols if set up properly.

If you are changing PlanType in code, you may need to implement the
INotifyPropertyChanged interface in your business objects.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top