Monday, May 5, 2008

ASP.NET 2.0 Databinding, Part I

This is the first of a series of posts about databinding in ASP.NET 2.0. These posts are mostly for my understanding and writing practice, but hopefully someone gets value out of them as well. To whoever does read this, I would love to hear some feedback.

The features I will be talking about are covered in a set of tutorials by Scott Mitchell that are much deeper and more detailed than these posts.

In ASP.NET 1.1, databinding was a manual, one way operation. You set the DataSource of a UI control to a collection and call DataBind. This is great, but what about getting the data back from the UI control? You have to manually access the values from the control and write code to map the values back to some kind of object.

In ASP.NET 2.0, there is support for two way databinding. What do I mean by two way? When a command is issued to a bound control, it will check if the DataSource object it is bound to supports the given command. If it does, the data will be passed back to the datasource control which will handle the operation (update, insert, delete).

This implementation has several parts. First, all data-bound controls now have a DataSourceID property. This property should correspond the ID property of a DataSourceControl object. These controls handle calling DataBind on the control and can be configured to handle most of the command events for a bound control (Edit, Update, Cancel, Delete, and Insert). Keep in mind that although DataSourceControl objects are part of the System.Web.UI namespace, they do not render anything themselves.

For the datasource to work, you must at least configure it to handle fetching data. For an ObjectDataSource, this means pointing it to an instance method that it should call to fetch the data. For a SqlDataSource, you have to give it a connection string and a select statement.

In part II, I will show how to use an ObjectDataSource in conjunction with TableAdapters (another ASP.NET 2.0 feature), to allow CRUD operations against a SQL Server database without writing a single line of C# code.

No comments: