在DropDownList中使用enum的方法

2010-08-28 10:44:42来源:西部e网作者:

平常我们用个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时候,那就比较方便了。

关键词:DropDownList