Jake Smith Jake Smith - 13 days ago 5x
C# Question

When setting the DataSource property of an object, when do you use a Type vs. an instance?


What is the difference between setting a
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();

Further inquery

Also, in the first case, if I set a
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

I'm having a hard time wording my
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.