枚举的转换、遍历和绑定到DropDownList

枚举

    enum month
    {
        Jan=1,
        Feb=2,
        Mar=3,
        Apr=4,
        May=5,
        Jun=6,
        Jul=7,
        Aug=8,
        Sep=9,
        Oct=10,
        Nov=11,
        Dec=12
    }

转换

        month m1 = (month)Enum.Parse(typeof(month), "Jun");
        month m2 = (month)6; //强制类型转换
        string m3 = Enum.GetName(typeof(month), 1);
        int m4 = (int)Enum.Parse(typeof(month), "Jun");
        int m5 = (int)month.Jun;
        
        Response.Write(string.Format("m1:{0}<br>m2:{1}<br>m3:{2}<br>m4:{3}<br>m5:{4}", m1, m2, m3,m4,m5));

输出的结果是:

m1:Jun
m2:Jun
m3:Jan
m4:6
m5:6 

绑定DropDownList

            Type type1 = typeof(month);
            ArrayList al = new ArrayList();
            foreach (int item in Enum.GetValues(type1)) //遍历枚举
            {
                //al.Add(new ListItem(((month)Convert.ToInt32(item.ToString())).ToString(), item.ToString()));
                al.Add(new ListItem(Enum.GetName(type1, item), ((int)Enum.Parse(typeof(month), item.ToString())).ToString()));
            }
            this.DropDownList1.DataSource = al;
            this.DropDownList1.DataValueField = "value";
            this.DropDownList1.DataTextField = "text";
            this.DropDownList1.DataBind();

 

量的积累到质的飞越

原文地址:https://www.cnblogs.com/taobox/p/2622645.html