DataBinding to an Enumeration / enum (C#, ASP.NET)

Enumeration types in C# can be used for many purposes. One such use is to reduce repetitive typing as they can be bound to server controls (e.g. Repeaters).

In code behind:

public enum WeekDays
{
 Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
}

In your page:

<asp:Repeater runat="server" DataSource='<%# Enum.GetValues(typeof(WeekDays)) %>'>
 <HeaderTemplate>
 <table>
 <thead>
  <tr>
   <th>Day</th>
   <th>Start Time</th>
   <th>End Time</th>
  </tr>
 </thead>
 <tbody>
 </HeaderTemplate>
 <ItemTemplate>
  <tr>
   <td><%# Container.DataItem %></td>
   <td><%# GetStartTime(Container.DataItem) %></td>
   <td><%# GetEndTime(Container.DataItem) %></td>
  </tr>
 </ItemTemplate>
 <FooterTemplate>
 </tbody>
 </table>
 </FooterTemplate>
</asp:Repeater>

GetStartTime and GetEndTime are just examples (so would just need writing in the code behind).

protected string GetStartTime(object day)
{
....
}
protected string GetEndTime(object day)
{
....
}

Comments

Anonymous said…
thanks for this!

Popular posts from this blog

Select box manipulation with jQuery

iTextSharp: Generating a Basic PDF file (ASP.NET/C#)

Popup Window Countdown (JavaScript)