Support for dropdownlist of enumerated data sources

Source: Internet
Author: User
[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.