[Download source code]
When using ASP. when developing Web applications, users often need to select a member from the enumeration type and use dropdownlist to handle this scenario. However, dropdownlist also has some restrictions, so that it does not provide good support for enumeration types. For example, you can use the enum. getnames () method to bind the text of the enumerated member to the dropdownlist as a data source, but cannot bind the value of the member. Therefore, the enumdropdown control that supports enumeration data sources is designed.
We mainly implement the above functions by rewriting the datasource attribute of the dropdownlist type and the databind () method.
Override datasource Properties
Override the datasource property to the type so that the control can obtain the enumerated type to be bound. Private type m_enumtype;
Public New Type datasource
{
Get
{
Return m_enumtype;
}
Set
{
M_enumtype = value;
}
}
Get Data Source
Considering that you need to bind both the text and value of the enumerated member and the convenient conversion between the enumerated member and the integer, use dictionary <string, int> type packages the data read from the given Enumeration type as the dropdownlist data source.
Private dictionary <string, int> getdatasource ()
{
Dictionary <string, int> retval = new dictionary <string, int> ();
String [] enumnames = enum. getnames (m_enumtype );
For (INT I = 0; I <enumnames. length; I ++)
{
Retval. Add (enumnames [I], (INT) enum. parse (m_enumtype, enumnames [I]);
}
Return retval;
}
Override the databind Method
Public override void databind ()
{
Base. datasource = getdatasource ();
Datavaluefield = "value ";
Datatextfield = "key ";
Base. databind ();
}
Reference: http://aspalliance.com/1514_Extending_the_DropDownList_to_Support_Enums