In this article I will explain with example, how to bind Repeater control using
Entity Framework in ASP.Net using C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Configuring and connecting Entity Framework to database
HTML Markup
The following HTML Markup consists of an ASP.Net Repeater control.
The Repeater control has the following templates:-
HeaderTemplate – The content of this template will not be repeated and will be placed in the top most position i.e. head section of the Repeater control.
ItemTemplate – The content of this template will be repeated for each record present in its DataSource.
AlternatingItemTemplate – AlternatingItemTemplate is used for adding alternate items. It is used along with ItemTemplate, generally for displaying a different design for alternating items.
SeparatorTemplate - This template is used to add a separator between two items of the Repeater control.
FooterTemplate – The content of this template will not be repeated and will be placed in the bottom most position i.e. footer section of the Repeater control.
<asp:Repeater ID="rptCustomers" runat="server">
<HeaderTemplate>
<table cellspacing="0" rules="all" border="1">
<tr>
<th scope="col" style="width: 80px">Customer Id</th>
<th scope="col" style="width: 120px">Customer Name</th>
<th scope="col" style="width: 100px">Country</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblCustomerId" runat="server" Text='<%# Eval("CustomerId") %>' />
</td>
<td>
<asp:Label ID="lblContactName" runat="server" Text='<%# Eval("ContactName") %>' />
</td>
<td>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Populating Repeater control in ASP.Net
Inside the
Page Load event handler, the Top 10 records from the Customers table is fetched using
Entity Framework and assigned to the
DataSource property of the Repeater control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
using (NorthwindEntities entities = new NorthwindEntities())
{
rptCustomers.DataSource = (from customer in entities.Customers.Take(10)
select customer).ToList();
rptCustomers.DataBind();
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Using entities As NorthwindEntities = New NorthwindEntities ()
rptCustomers.DataSource = (From customer In entities.Customers.Take(10) Select customer).ToList()
rptCustomers.DataBind()
End Using
End If
End Sub
Screenshot
Demo
Downloads