平常我們用個DropDownList,一般都像這樣寫:
<asp:DropDownList id="xl" runat="server">
<asp:ListItem Value="0">小學</asp:ListItem>
<asp:ListItem Value="1">中學</asp:ListItem>
<asp:ListItem Value="2">大學</asp:ListItem>
</asp:DropDownList>
現在我們可以用枚舉來寫這樣:
先定義一個enum:
public enum 學歷
{
小學 = 0,
中學 = 1,
大學 = 2
}
好玩的是.net里還支持中文的變量。
然后根據enum來動態創建DropDownList,方法一:
x1.DataSource=Enum.GetValues(typeof(學歷));
x1.DataBind();
麻煩一點的方法二:
foreach(學歷 _xl in Enum.GetValues(typeof(學歷)))
{
xl.Items.Add(new ListItem(_xl.ToString(), Convert.ToInt32(_xl).ToString()));
}
如果我們有多個地方用到同樣的DropDownList時候,那就比較方便了。