Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

What You Need to Know About Web Controls

Knowing the flaws in Web server controls and how to work around them before you use them can save you hours of time.


advertisement
ne of the key tenets of .NET is that it makes developers more productive. And this is basically true—it is easier to build applications, including Web applications. You can build a complex Web page with its associated business object and stored procedures in less than four hours. But then you waste two days trying to get a particular Web control to work as you need it to—not very productive!

This article looks at several Web server controls, identifies the features of the control that do not work as expected or are challenging to make work, and provides work-arounds for these issues. Specifically, this article will show you how to fill a DropDownList from an Enum, display a CheckboxList control with the correct style, and get the Calendar control to work like a date picker.

Fill a DropDownList from an Enum
The DropDownList is a Web server control that allows an end user to select one or more items from a list. You can bind the DropDownList to a database, and the .NET online help provides many examples of how to do that. But it is more challenging to find sample code for populating a DropDownList from an Enum.

Start by putting a DropDownList on a Web form, such as the User Type DropDownList shown in Figure 1. To match this example, define the DropDownList with an ID of cboUserType.

 
Figure 1: This Web form provides an example of the controls discussed in this article.
In the code-behind for the Web form, define an Enum named UserTypeEnum to provide the set of user types as follows:

Private Enum UserTypeEnum Administrator = 0 Gold_Customer = 1 Silver_Customer = 2 Bronze_Customer = 3 Visitor = 4 End Enum


Add the code to populate the control as a method in the code-behind for the Web form:

Private Sub FillUserType() ' Loop through the entries in numerical order For Each iValue As Int32 In _ System.Enum.GetValues(GetType(UserTypeEnum)) Dim li As New ListItem li.Value = iValue.ToString li.Text =[Enum].GetName(GetType(UserTypeEnum), _ iValue).Replace("_", " ") li.Selected = False cboUserType.Items.Add(li) li = Nothing Next End Sub


The GetValues method of the Enum class retrieves an array of the UserTypeEnum constant values. The For/Each loop iterates through each array entry creating an associated ListItem, which defines the contents of the DropDownList.

Note that this code must create a new ListItem object for each item to be added to the DropDownList. Otherwise, all of the items added to the DropDownList will reference the same item. To see this incorrect behavior, move the line of code that creates the new instance of ListItem to before the For/Each loop and remove the code that sets the ListItem to Nothing. You will then see that the DropDownList contains the "Visitor" item five times.

The ListItem has two key properties. The Text property is the text that will appear in the list and the Value property is the value that will be assigned to the control if the entry is selected. In this example, the enumeration constant is assigned to the Value property.

The GetName method of the Enum class provides the name of the enumeration that is associated with the defined value. For example, the UserTypeEnum value of "1" has an associated name of "Gold_Customer". It is not desirable to display the underscore (_) character to the end user, so the Replace method of the String object replaces the underscore with a space.

The Selected property is initially set to False for each item. By default, the first item is automatically selected in the list when the page is displayed. To specify which item should be initially selected, add the following line after the Next statement:



cboUserType.SelectedValue = _ CType(UserTypeEnum.Visitor, Int32).ToString


Completing the process, the ListItem is added to the DropDownList Items collection and the ListItem is set to Nothing. The loop repeats until all of the Enum values are processed.

Notice that in some cases the code refers to System.Enum and other times it uses [Enum]. Since by default a Web project has a reference and project import for System, the System namespace prefix is not needed. But Enum by itself is a reserved keyword used for the Enum statement as shown in the first code listing in this article. To distinguish the Enum class name from the Enum keyword, enclose the class name within brackets ([ ]).

If you instead want the values to appear in the DropDownList in alphabetical order, sort them as follows:

Private Sub FillUserType() ' Loop through the entries in alphabetical order Dim arr As Array arr = System.Enum.GetNames(GetType(UserTypeEnum)) Array.Sort(arr) For Each sName As String In arr Dim li As New ListItem li.Value = CType([Enum]. _ Parse(GetType(UserTypeEnum), sName), _ Int32).ToString li.Text = sName.Replace("_", " ") li.Selected = False cboUserType.Items.Add(li) li = Nothing Next End Sub


This code loops through the Enum names instead of the values. So the Text property of the ListItem is assigned to the Enum name directly (removing any underscores). The Parse method of the Enum class is used to obtain the value of the Enum, given the name. The result is assigned to the Value property of the ListItem. The remainder of the code in the loop is the same as the prior code listing.

To complete the final step in this example, call the FillUserType method when the page is loaded:

Private Sub Page_Load(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles MyBase.Load 'Put user code to initialize the page here ' The first time through, load the combo If Not Page.IsPostBack Then ' Fill the User Type FillUserType() End If End Sub


This code uses the IsPostBack method of the Page to call FillUserType the first time the page is loaded. If the page is reloaded due to a post back, the DropDownList is automatically repopulated from the ViewState.

When the end user selects an item, your code has the option of processing the selection immediately or processing the selection when the end user submits the page. For better performance, you normally want to process the selection when the end user submits the page, which is the default.

However, there are times when you need to process the end user's selection immediately. For example, you may want to change the contents of other controls based on the selection in the DropDownList. When this is the case, you can set the AutoPostBack attribute of the control to True.

This example demonstrated how to leverage enumerations and display enumerated values in a DropDownList. By understanding the many properties and methods of the Enum class, you will find many other uses for Enums in your applications.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap