Sun
Sun

Reputation: 4708

Databinding issue in C#

I have an issue with DataBindings in C#.

I have a BindingSource with it's DataSource set to a DataRowView

I then use the binding source to set all the databinding for my controls.

Here is my code:

bsDataRecord.DataSource = myDataRow; //bsDataRecord is a BindingSource and myDataRow is a DataRowView
//Add Databinding to my controls
dateNextDate.DataBindings.Add("Value", bsDataRecord, "Next_Date", false, DataSourceUpdateMode.OnPropertyChanged); //DateTimePicker
textInformation.DataBindings.Add("Text", bsDataRecord, "Information", false); //TextBox
//more controls, etc

My databindings all work fine. So as I select the control and enter a value, myDataRow is updated.

My problems occurs when I try to set a control's value in code e.g.

textInformation.Text="Test";

When I do this myDataRow isn't updated. The only way I can get myDataRow to update is to give the control that I've updated focus.

Hope that makes sense!? Anybody got any ideas?

Thanks in advance.

I'm using c#.Net 4.0.

Upvotes: 1

Views: 998

Answers (2)

Wanabrutbeer
Wanabrutbeer

Reputation: 697

After problematically setting a property of the data source, you need to get the controls to reread their values from the datasource. Often a simple call to

dataBindingSource.ResetBindings(false); // false for value change not schema change

But you could also per control use this:

foreach (Binding b in myControl.DataBindings) b.ReadValue();

Binding.ReadValue() causes the control's bound property to be set to the data source value

Hope this helps!

Upvotes: 2

Nicolas Voron
Nicolas Voron

Reputation: 2996

If you update a (non-two-way)binding's target "by hand", that breaks the binding and it will not work anymore. This is normal behaviour.

So make your binding two-way to achieve what you want to do.

Upvotes: 0

Related Questions