Also read Avoid DataBinder.Eval in ASP.NET and improve Performance
For this demonstration, I am using Windows 7 and Visual Studio 2012.
Let’s first create a blank web site using Visual Studio 2012 with the name “StronglyTypedDataControlDemo” as shown below –
Now let’s add a new item which uses web form in our blank website with the default name “Default.aspx”. Now add a Repeater control in our “Default.aspx” as shown below –
If you observe the code, we have a “Header Template” and “Footer Template” as well we our “Item Template”. The “Item Template” is currently blank. Let’s design the item template as it’s usually done –
Now let’s add a new database “ExampleDB” and add a new table in the same database with the name “Customers” with following columns specifications –
Add a new class, which is “LINQ to SQL” in our web site with the name “CustomerInformation.dbml” as shown below –
Now drag and drop customers table into our "CustomerInformation.dbml".
Add the following code into our code file -
Run your web site and you will see the output as shown below -
Let's change the field name which we have passed to our "Eval" Expression and misspell it. After this change, compile the application and you will see the application gets compiled successfully.
If you observe, I have misspelled the "ContactName" to "ContacName" and my web site still gets complied. But if you run the web page, you will get an error as shown below -
To avoid similar issues where developers may misspell field names, ASP.NET 4.5 has come up with Strongly Typed Data Controls.
Now let's set a new property in our repeater control which is "ItemType" to "Customer" and replace the "Eval" expression with the "Item.ContactName" as shown below -
Note: Observe the intellisense when you set ItemType as well as when say Item followed by a dot(.) -
Now replace all Eval, with Item.ContactName, Item.State and Item.Country respectively and run your web page and you should see the same expected output as shown below -
Now try to misspell the column/field name, and you will instantly see a red line below the field and if you compile the application, you will get errors in "Error List" window as shown below -
How very convenient!
Summary - In this article, we have seen how to use the new Strongly Typed Data Controls compared to Eval expressions in ASP.NET 4.5.
Download the source code (GitHub)