ASP.NET 4.5 has introduced some cool new features and enhancements for web developers using Visual Studio 2012. One of the new features introduced deals with the framework’s Web Forms technology. In previous versions of ASP.NET, if you wanted to display data-bound values in a control, you needed to use a data-binding expression with an Eval statement, e.g.
<%# Eval(“Data”) %>.
This approach works, but it introduces a few problems. In my experience, the Eval statement approach is prone to developer error. If you are like me, then you have undoubtedly misspelled a member name or tried to bind to a nonexistent member. These mistakes, while trivial, tend to make themselves known only at run-time thus making them more difficult to track. Due to the Eval statement being dynamic in nature, it is impossible to enforce compile time error checking.
With ASP.NET 4.5, we can now take advantage of Strongly Typed Data Controls. These controls allow us to specify the type of data the control is to be bound to, providing us with IntelliSense (which solves another problem for me: remembering which members belong to the DataSource) and compile time error checking. Adding a strongly typed data control requires minimal effort!
To get started, place the data control you want to work with on your Web Form. In my project, the
StronglyTypedDataControl.aspx page contains a repeater that will be data-bound. (Please click on any image below to see it full-size.)
In the corresponding page’s code behind, you will need to create a public method of type
IEnumerable<out t> that returns the data needed by your control. As you can see, I am simply returning the list,
employees. Using this approach, you will still need to bind your control to the data source, so I am calling the
DataBind() method on the repeater
To make the data control strongly typed, simply set the control’s
ItemType property to the class you will be using. In my case, I am using the
Now you will need to tell the control what method to call in order to retrieve data. To do this, set the control’s
SelectMethod property to the method that returns an object of type
IEnumberable<out t>. In my project I defined the method
GetEmployees() to do this. Once this is done, the control exposes a property called
Item that represents the objects of the type specified in the
ItemType property. As you can see, the
Item property behaves the same way as an instance of the class
Employee would behave.
You can download the demo project from GitHub.