Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Question

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.

Example

How does

object1.DataSource = typeof(SomeClass);

differ from

object2.DataSource = getSomeObject();

Further inquery

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!

like image 460
Jake Smith Avatar asked Aug 18 '14 17:08

Jake Smith


2 Answers

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.

like image 149
Martin Liversage Avatar answered Sep 23 '22 01:09

Martin Liversage


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.

like image 39
helgeheldre Avatar answered Sep 23 '22 01:09

helgeheldre