Binding a Dropdownlist to Enumeration Values in ASP.NET

<%@ Page Language="C#" %>  

<%@ Import Namespace="System" %>  
<%@ Import Namespace="System.Web" %>  
<%@ Import Namespace="System.Web.UI" %>  
<%@ Import Namespace="System.Web.UI.WebControls" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  

<script runat="server">  
  public void AddEnumToList(Type GetSystemType, ListControl List)  
  {  
      // Populates the specified list with the   
      // names and values of the passed system type   
      string[] strNames;  
      System.Array arrValues;  
      int intCount;  
      strNames = Enum.GetNames(GetSystemType);  
      arrValues = Enum.GetValues(GetSystemType);  
      List.Items.Clear();  
      for (intCount = strNames.GetLowerBound(0); intCount < strNames.GetUpperBound(0); intCount++)  
      {  
          List.Items.Add(new ListItem(strNames[intCount].ToString(), arrValues.GetValue(intCount).ToString()));  
      }  
  }  

  public enum Test  
  {  

      Jan,  
      Feb,  
      March,  
      April,  
      May,  
      June,  
      July,  
      August,  
      September,  
      October,  
      November,  
      December  

  }  


  protected void Page_Load(object sender, EventArgs e)  
  {  
      Test a = new Test();  
      AddEnumToList(typeof(Test), DropDownList1);  
  }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
  <title>Untitled Page</title>  
</head>  
<body>  
  <form id="form1" runat="server">  
      <div>  
          <asp:DropDownList ID="DropDownList1" runat="server">  
          </asp:DropDownList></div>  
  </form>  
</body>  
</html>

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru