views:

489

answers:

2

Simple question, I guess.

For a long time I've blindly followed a (supposedly) common pattern when programmatically databinding my ASP.NET controls. Namely:

gridView1.DataSource = someList;
gridView1.DataBind();

However, if I were setting my GridView to bind to a DataSource control via the DataSourceID property, the call to DataBind() is unnecessary. Namely:

gridView1.DataSourceID = LinqDataSource1;

is sufficient.

Furthermore, if you try to set the DataSource property in ASPX markup, you are greeted with the following:

You cannot set the DataSource property declaratively.

I assume these are related, but I am still stumped as to why DataBind() is necessary. The difference between DataSource and DataSourceID is secondary - I can understand some magic taking place there. The real question is why doesn't the DataSource propery setter cause databinding automatically? Are there any scenarios in which we want to set the DataSource but not bind to it?

+3  A: 

In ASP.Net, it's often important to have certain data available and ready at certain points in the page life cycle, and not before. For example, you may need to bind to a drop down list early to allow setting the selected index on that list later. Or you might want to wait a bit to bind that large grid to reduce the amount of time you hold that connection active/keep the data in memory.

Having you explicity call the .DataBind() method makes this possible.

Joel Coehoorn
Can you explain how binding later causes a shorter time in keeping the data in memory? I assume for a simple Collection kept in memory (as above, if someList is List<object>) there is no difference, but how does it work for something more complicated? Is there delayed evaluation? An example would be excellent.
JoshJordan
Think of using an datareader as the source. If you bind right away, you'll iterate over the reader and have those contents in memory. If you wait for later in the page lifecycle, you hang on to it for less time.
Joel Coehoorn
A: 

DataSource is a property of the BaseDataBoundControl class. DataSourceID is a property of the DataBoundControl class, which inherits from BaseDataBoundControl and did not exist before ASP.NET 2.0.

Since DataBoundControl is explicitly for displaying data in a list or tabular form, and BaseDataBoundControl cannot make that assumption, binding is not automatic when DataSource is set because the type of control may not match the structure of the data.

Of course, this is all just a guess based on the MSDN documentation, so I could be wrong.

Matthew Jones