ASP.NET 4.5 Strongly Type Data With Data Controls

Introduction

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">
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Item.Name %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:Label ID="lblCity" runat="server" Text='<%# Item.Salary%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>


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

ASP1.jpg

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>();
            ListEmp.Add(
new Employee { ID = 1, Name = "Amit", Salary = 100000000 });
            ListEmp.Add(
new Employee { ID = 2, Name = "Ram", Salary = 100000000 });
            ListEmp.Add(
new Employee { ID = 3, Name = "Raju", Salary = 100000000 });
            ListEmp.Add(
new Employee { ID = 4, Name = "kumar", Salary = 100000000 });
            myGridView.DataSource = ListEmp;
 
            myGridView.DataBind();
}

Step 4: The output screen:

ASP2.jpg

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

Up Next
    Ebook Download
    View all
    Learn
    View all