Enumerations are extremely valuable for managing sets of numeric values such as status codes or days of the week. Most of the time, you would create an enumerable to simplify values used in multiple points that have the same representation, in order to improve the readability and re-usability of your code. However, there are some situations where using the enumeration’s name and value directly on the presentation layer can make sense.
For example, let’s say we have a form where we need the user needs to choose a day of the week to assign to a particular record. We can easily generate a drop down list of values using the built in DayOfWeek enum that is included by default in the System library.
Let’s create a Drop Down List on our page. We will generate the list items in code behind, so we will just leave those blank. It should look something like this:
<br /><asp:DropDownList ID="ddlDay" runat="server"></asp:DropDownList><br />
In our code behind file, we will use a couple of helpers from the System.Enum namespace to allow us to loop through our enumerable’s values and get their names for use in the list item. Here’s the code for our page load event:<br />Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load<br /><%%KEEPWHITESPACE%%> If Not Page.IsPostBack() Then<br /><%%KEEPWHITESPACE%%> ' Get the values of the DayOfWeek Enum (0-6).<br /><%%KEEPWHITESPACE%%> Dim daysOfTheWeek = System.Enum.GetValues(GetType(DayOfWeek))<br /><br /><%%KEEPWHITESPACE%%> For Each value In daysOfTheWeek<br /><%%KEEPWHITESPACE%%> ' Get the name that corresponds to each value.<br /><%%KEEPWHITESPACE%%> Dim name = System.Enum.GetName(GetType(DayOfWeek), value)<br /><br /><%%KEEPWHITESPACE%%> ' Add a new list item, using our name and value.<br /><%%KEEPWHITESPACE%%> ddlDay.Items.Add(New ListItem(name, value))<br /><%%KEEPWHITESPACE%%> Next<br /><%%KEEPWHITESPACE%%> End If<br />End Sub<br />
It’s that simple. Now you know that the value that gets posted back to the server will match directly with the values defined in the enumeration, even if the values were to change at a later date.
One thing to keep in mind are that this is only a user friendly option for single word names. For example, if you have a value that represents a process’ status that is named “InProgress”, it would appear as a single word in the drop down as well. You could parse the name to add the space, but there are cases where that could over complicate the process.
Thanks for reading!