Jan 28
2009

Um eine ASP.NET DropDownList mit Werten aus einem Enum zu füllen, gibt es unterschiedliche Ansätze.

Beispielsweise kann das Enum für einen LoginStatus folgendermaßen aussehen:

/// <summary>
/// enum for login status
/// </summary>
public
enum LoginState
{
  Inactive = -1,
  Active = 1,
  Deactivated = 2
}

Um das DropDown mit den Werten des Enum zu füllen, sind zwei Zeilen Code ausreichend:

/// <summary>
/// fills ddlContactPersonLoginState
/// </summary>
private void FillContactPersonLoginStateDropDown()
{
  ddlContactPersonLoginState.DataSource =
Enum.GetNames(typeof(LoginState));
  ddlContactPersonLoginState.DataBind();
}

Allerdings hat diese Lösung zur Folge, dass value und key im DropDown gleich sind.

 

Ein anderer Ansatz über eine Hilfsmethode erlaubt es, value und key separat zu ermitteln
und dem DropDown als DataValueField und DataTextField zuzuweisen:

/// <summary>
/// helpermethod to store enum values and their corresponding names in a SortedList
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static SortedList<string, int> GetEnumDataSource<T>() where T : struct
{
 
Type myEnumType = typeof(T);
 
if (myEnumType.BaseType != typeof(Enum))
  {
   
throw new ArgumentException("Type T must inherit from System.Enum");
  }

  SortedList<string, int> returnCollection = new SortedList<string, int>();
 
string[] enumNames = Enum.GetNames(myEnumType);

  for (int i = 0; i < enumNames.Length; i++)
  {
    returnCollection.Add(enumNames[i], (
int)Enum.Parse(myEnumType, enumNames[i]));
  }
  return returnCollection;

}

Das Füllen des DropDowns muss jetzt etwas erweitert werden:

/// <summary>
/// fills ddlContactPersonLoginState
/// </summary>
private
void FillContactPersonLoginStateDropDown()
{
 
ddlContactPersonLoginState.DataSource = GetEnumDataSource<LoginState>();
 
ddlContactPersonLoginState.DataValueField = "Value";
  ddlContactPersonLoginState.DataTextField ="Key";
  ddlContactPersonLoginState.DataBind();
}

Jetzt stehen im DropDown Value und Key für die weitere Verarbeitung zur Verfügung.

Tags:

Related posts

Comments

cash loans

Posted on Saturday, 24 October 2009 01:04

Yea nice Work !:D

personal loans

Posted on Tuesday, 3 November 2009 20:59

Searching for this for some time now - i guess luck is more advanced than search engines :)

Comments are closed