In this article I will explain with an example, how to format DateTime field in dd/MM/yyyy format in ASP.Net Repeater using C# and VB.Net.
HTML Markup
The HTML Markup consists of an ASP.Net Repeater control rendered as an HTML Table with three columns.
The DateTime field value is converted to dd/MM/yyyy by passing an additional parameter i.e. {0:dd/MM/yyyy} in order to format and display the DateTime field value in dd/MM/yyyy format.
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table cellspacing="0" rules="all" border="1">
<tr>
<th scope="col" style="width: 30px">Id</th>
<th scope="col" style="width: 150px">Name</th>
<th scope="col" style="width: 150px">Birth Date</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Id")%></td>
<td><%# Eval("Name")%></td>
<td><%# Eval("BirthDate", "{0: dd/MM/yyyy}")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Namespaces
You will need to import the following namespace.
C#
VB.Net
Populating the Repeater control
Inside the Page Load event, the Repeater control is populated with a DataTable containing some dummy records.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("BirthDate",typeof(DateTime)) });
dt.Rows.Add(1, "John Hammond", new DateTime(1975, 12, 1));
dt.Rows.Add(2, "Mudassar Khan", new DateTime(1985, 2, 25));
dt.Rows.Add(3, "Suzanne Mathews", new DateTime(1992, 3, 23));
dt.Rows.Add(4, "Robert Schidner", new DateTime(1982, 1, 15));
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("BirthDate", GetType(DateTime))})
dt.Rows.Add(1, "John Hammond", New DateTime(1975, 12, 1))
dt.Rows.Add(2, "Mudassar Khan", New DateTime(1985, 2, 25))
dt.Rows.Add(3, "Suzanne Mathews", New DateTime(1992, 3, 23))
dt.Rows.Add(4, "Robert Schidner", New DateTime(1982, 1, 15))
Repeater1.DataSource = dt
Repeater1.DataBind()
End If
End Sub
Screenshot
Demo
Downloads