What is the difference between setting a [...].DataSource
to an instance of an object vs. the type of a class? I have seen both methods in use in our codebase, and I'm trying to wrap my head around why it is one way or the other in any of these cases.
How does
object1.DataSource = typeof(SomeClass);
differ from
object2.DataSource = getSomeObject();
Also, in the first case, if I set a DataSource
to be the type of a class, what happens if that class is a base class? Does the data binding work on properties that only exist in classes that descend from the base class? Or does the data binding only work on the class members of the type of the class I set the DataSource
to?
I'm having a hard time wording my Google
search queries to give me an answer to this question. And that is either because this stuff is complicated and I'm just not wording it right, or I do not quite understand some of the fundamentals of data binding in C#. Could I get some help getting pointed in the right direction here? Thanks!
When you set the BindingSource.DataSource
property to a type the control is bound to an empty IBindingList
with elements of that type. So the data source will initially have no items. If on the other hand you set the DataSource
to a collection of items the data source will be bound to an IBindingList
with these items.
So assigning a type gives you an empty list of items while assigning a collection gives you a list with items from the collection.
If you assign a base type you get an empty list of base type items. The data binding does not "know" about any derived classes.
If you set the datasource to be of a type you define what kind of type you will be handling later. This will help in binding properties from that object to elements in the designer.
Setting the value is needed at a later stage to define what data will actually be shown.
Edit: And you can only access properties that is on the class you are handling, not any parent classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With