Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Architecture
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
Bing
BizTalk
Book Excerpts
Build and Deploy
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Design Patterns
Development Process
Display Technologies
Distributed Computing
DotNetNuke
DSL
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
Internet Explorer 8.0
Interviews
iPhone
Iron Ruby
Java
Java Script
jQuery
LINQ
Linux
Mac OS X
MDX
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
Network
NHibernate
Object Oriented Development
Odata
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Python
Q&A
Rails
Rake
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Search
Security
Services
SharePoint
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
Tips
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WF
Whitepapers
Windows 7
Windows Azure
Windows Live
Windows Server
Windows Vista
WinForms
Workflow
WPF
XAML
XML
XNA
XSLT



CODE Training


 


Free Webinar

Reader rating:
Click here to read 6 comments about this article.
Article source: CoDe (2005 - Mar/Apr)


Article Pages:  1  2 3 - Next >


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.

One 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!

"
It is often not the every-day coding that impacts our productivity and causes us to miss our deadlines and overrun our budgets. Rather, it is how quickly we can find answers when .NET does not provide us with the results we expected.
"

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 the 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".

Click for a larger version of this image.

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 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 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.

&

By: Deborah Kurata

Deborah Kurata is cofounder of InStep Technologies Inc., a professional consulting firm that focuses on turning your business vision into reality using Microsoft .NET technologies. She has over 15 years of experience in architecting, designing and developing successful applications.

Deborah is the author of several books, including Best Kept Secrets in .NET (Apress), Doing Objects in Visual Basic 6.0 (SAMS) and Doing Web Development: Client-Side Techniques (Apress). She is on the INETA Speaker’s Bureau, is a well-known speaker at technical conferences, and is a Microsoft Most Valuable Professional (MVP). After a hard day of coding and taking care of her family, Deborah enjoys blowing stuff up (on her XBox of course).

Some of the information in this article was obtained from her upcoming book, Doing Objects in VB 2005.

deborahk@insteptech.com

Fast Facts

Google (www.google.com) is always a good place to start if you get stuck and cannot make a Web Server control perform as you desire.



Article Pages:  1  2 3 - Next Page: 'Setting Styles in a CheckboxList' >>

Page 1: What You Need to Know about Web Controls
Page 2: Setting Styles in a CheckboxList
Page 3: Working with the Calendar

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
3.3 out of 5

22 people have rated this article.

      INSTANTLY dtSearch® TERABYTES OF TEXT

 

Free Webinar