将一个枚举类型动态绑定到一个列表控件的方法
2011-01-04 11:37
483 查看
我们在做项目的时候经常需要将定义的枚举类型动态绑定到列表控件中,例如DropDownList控件。下面的方法可以满足题目的需求
(本题是将这个类放在App_Code中)
下面给出如何调用此方法
前台
后台
(本题是将这个类放在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 } }
相关文章推荐
- MFC中动态创建列表控件及其刷新重绘的方法
- 列表控件扩展方法绑定
- vue.js给动态绑定的radio列表做批量编辑的方法
- 总算知道java的列表为何要设一个专用的枚举类型Iterator了
- MVC 中将枚举类型绑定到下拉列表
- MVC中将枚举类型数据应用到下拉列表中的方法
- 如何动态清理一个控件事件上附加的所有方法
- winform有一个combobox和一个textbox控件,如何进行动态绑定,使得combobox中的数据改变时,textbox中的数据也随之改变?
- MFC-为动态控件绑定事件方法1
- C#中PropertyGrid控件绑定对象后更改属性值写回到xml中的一个有效方法
- MFC-为动态控件绑定事件方法1
- ASP.NET中DropDownList下拉框列表控件绑定数据的4种方法
- 使用泛型, 写一个为任意类型的动态数组添加元素的方法
- 求动态绑定控件ID的值的方法!着急!
- asp.net下的“Eval()、XPath() 和 Bind() 这类数据绑定方法只能在数据绑定控件的上下文中使用。”错误的一个可能的成因
- VB.Net自己写的一个控件:ComboBox下拉列表中显示多列数据(可以绑定数据表)
- MVC中将枚举类型绑定到下拉列表
- ASP.NET中DropDownList下拉框列表控件绑定数据的4种方法
- 枚举类型绑定下拉列表
- 将多个不同类型的控件放在一个动态数组(ArrayList)中作为参数(控件数组)传递