Reader Level:

ASP.NET 4.5 Strongly Type Data With Data Controls

By Amit Patel on Jun 01 2012
Today I am going through the new features of ASP.NET 4.5.
    • Like
    • Love It
    • Awesome
    • Interesting
    • It's Okay
    • Thumbs Down
  • 21.5k
  • 0


Today I am going through the new features of ASP.NET 4.5. I have seen som fantastic features for Web Developers. Previously there was plenty of trouble when binding any data controls from a data source. If you are using an item template with any Model, then that Model was not tightly coupled with the Data Control.

But now in ASP.NET 4.5 we have a very good feature; now we can map a Data Control with a Strongly Typed Data Model. Microsoft exposes one new property for all Data Controls, called ItemType.

Code: Let's see a sample use for the ItemType and Data Controls. In my example I am using a GridView control; you can use any Data Control like DataList, Repeater etc.

Step 1: First we will create a Model Class.

namespace SampleForASPNET45_1
public class Employee
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }

Step 2: Now we will take a GridView control in the ASPX page:

<asp:GridView ID="myGridView" runat="server" AutoGenerateColumns="false" ItemType="SampleForASPNET45_1.Employee">
            <asp:TemplateField HeaderText="Name">
                    <asp:Label ID="lblName" runat="server" Text='<%# Item.Name %>'></asp:Label>
            <asp:TemplateField HeaderText="City">
                    <asp:Label ID="lblCity" runat="server" Text='<%# Item.Salary%>'></asp:Label>

See the following image of how the model property is populated.


Step 3: Now we will bind a GridView control with the DataSource:

protected void Page_Load(object sender, EventArgs e)
IList<Employee> ListEmp = new List<Employee>();
new Employee { ID = 1, Name = "Amit", Salary = 100000000 });
new Employee { ID = 2, Name = "Ram", Salary = 100000000 });
new Employee { ID = 3, Name = "Raju", Salary = 100000000 });
new Employee { ID = 4, Name = "kumar", Salary = 100000000 });
            myGridView.DataSource = ListEmp;

Step 4: The output screen:


Note: I just want to highlight one major point here; in previous releases Microsoft introduced the ModelType Property but they changed with ItemType.