您的位置:首页 > 其它

将一个枚举类型动态绑定到一个列表控件的方法

2011-01-04 11:37 483 查看
我们在做项目的时候经常需要将定义的枚举类型动态绑定到列表控件中,例如DropDownList控件。下面的方法可以满足题目的需求

(本题是将这个类放在App_Code中)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Data;

namespace DX.Common
{
/// <summary>
/// 此静态类提供了将一个枚举类型绑定到一个列表控件的方法
/// </summary>
/// <typeparam name="TEnum"></typeparam>
public static class EnumManager<TEnum> where TEnum : struct
{
private static DataTable GetDataTable()
{
Type enumType = typeof(TEnum); // 获取类型对象
FieldInfo[] enumFields = enumType.GetFields();    //获取字段信息对象集合

DataTable table = new DataTable();
table.Columns.Add("Name", Type.GetType("System.String"));
table.Columns.Add("Value", Type.GetType("System.Int32"));
//遍历集合
foreach (FieldInfo field in enumFields)
{
if (!field.IsSpecialName)
{
DataRow row = table.NewRow();
row[0] = field.Name;   // 获取字段文本值
row[1] = Convert.ToInt32(field.GetRawConstantValue());        // 获取int数值
//row[1] = (int)Enum.Parse(enumType, field.Name); 也可以这样

table.Rows.Add(row);
}
}
return table;
}

public static void SetListControl(ListControl list)
{
list.DataSource = GetDataTable();
list.DataTextField = "Name";
list.DataValueField = "Value";
list.DataBind();
}
}
}


下面给出如何调用此方法

前台

a<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<asp:DropDownList ID="ddlEnum" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>


后台

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DX.Common.EnumManager<MemoType>.SetListControl(ddlEnum);
}
}

/// <summary>
/// MemoType的枚举
/// </summary>
public enum MemoType
{
General = 0,
StoreCredit = 1,
UseCredit = 2,
ReturnPackage = 3,
Refund = 4,
AddItem = 5,
CancelItem = 6,
ChangeAddress = 7,
ChangeDeclaration = 8,
AddInvoice = 9,
Others = 99
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: