Non-binding binder source

I use bindingsource in my windows forms application to fill in some text fields, etc., in my opinion. Binding works fine, but how can I unsubscribe my bindingSource from my object?

bindingSource.DataSource = new Foo();//OK bindingSource.DataSource = null;//Not ok 

If I try to untie by setting data = null , I get an exception:

System.ArgumentException: Cannot bind to a property bar or column to a Data Source. Parameter Name: dataMember

I don’t want to delete all bindings to my controls (I have a lot of them), but I would like to suspend the binding if the bindingSource has no data ....

I found a workaround like this bindingSource.DataSource = typeof(Foo); but is this a way?

+6
source share
3 answers

The type of "workaround" is actually what the window designer does when you set the BindingSource data source to the PropertyGrid and select the type from "Project Data Sources".

Look at the generated code in the * .designer.cs file for your form.

We use this β€œtrick” in one of our products, and it has been working well for many years.

Hi

+5
source

I do not know the .Data property for the BindingSource object, but there is a .DataSource property that can be set to null:

 bindingSource.DataSource = null; 

This frees the data binding source. However, looking at the link for BindingSource.DataSource :

 DataSource property List results ---------------------------- ------------------------------------------- null with DataMember set Not supported, raises ArgumentException. 

If you use DataMember, you cannot set the DataSource to null without exception.

Unfortunately, I do not know if your workaround is the appropriate way, but at least now we know that you cannot just bind to null when the DataMember is set.

0
source

mrlucmorin gave you the correct answer. It works, and this is the right way to deal with this situation.

However, this will not work if your DataSource is of type DataTable. In this case, you can play with bs.RaiseListChangedEvents = false; before resetting BindingSource.DataSource and set to true after assigning a new DataSource. Immediately after you set to true, do not forget to reset the bindings with bs.ResetBindings(true);

Keep in mind that this may cause your data controls to contain old data.

0
source

Source: https://habr.com/ru/post/891650/


All Articles