How to Bind An Enum Name and Value to an ASP.NET DropDownList


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. enum Speed {
  2. Low = 1,
  3. Medium = 2,
  4. High = 3
  5. }
  6.  
  7. protected void Page_Load(object sender, EventArgs e) {
  8. Hashtable htSpeed = BindEnum(typeof(Speed));
  9. DropDownList1.DataSource = htSpeed;
  10. DropDownList1.DataValueField = "key";
  11. DropDownList1.DataTextField = "value";
  12. DropDownList1.DataBind();
  13. }
  14.  
  15. protected Hashtable BindEnum(Type speedEnum) {
  16. string[] enumNm = Enum.GetNames(speedEnum);
  17. int[] enumVal = (int[])Enum.GetValues(speedEnum);
  18. Hashtable htSpeed = new Hashtable();
  19. for (int cnt = 0; cnt < enumVal.Length; cnt++)
  20. {
  21. htSpeed.Add(enumVal.GetValue(cnt), enumNm[cnt]);
  22. }
  23. return htSpeed;
  24. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.