Thursday, June 3, 2010

Populating the DropDownList with Enum

Suppose you want to populate a DropDownList with Enum. Using System.Reflection it can be done as below

<asp:DropDownList ID="ddlPackageType" runat="server" Width="60">
</asp:DropDownList>

public struct PackageTypes
{
   public const string Document = "01";
   public const string Package = "02";
}

private void FilPackageType()
{
  FieldInfo[] myEnumFields = typeof(PackageTypes).GetFields();
  foreach (FieldInfo myField in myEnumFields)
  {
   if(!myField.IsSpecialName && myField.Name.ToLower() != "notset")
   {
     string myValue = (string)myField.GetValue(0);
     ddlPackageType.Items.Add(new ListItem(myField.Name, myValue.ToString()));
   }
  }
}

Download Article

No comments:

Post a Comment