将枚举类转换成datatable
By:Roy.LiuLast updated:2009-01-05
有一个枚举类;
public enum QuestionType
{
[Description("单选题")]
SingleChoice=0,
[Description("多选题")]
MultiChoices=1,
//[Description("填空题")]
//FillBlank = 2,
[Description("表格题")]
Table=3,
[Description("单选填空题")]
SingleBlank = 4,
[Description("问答题")]
AskAndAnswer = 5
}
要将起作为一个数据源,绑定到一个combox下拉框中.
处理方法如下:
public static DataTable GetQuestionTypeFromEnum()
{
DataTable dt = new DataTable("QuestionType");
dt.Columns.Add(new DataColumn("ID", typeof(System.Int16)));
dt.Columns.Add(new DataColumn("Name", typeof(System.String)));
Type questionType = typeof(Enum.QuestionType);
System.Reflection.FieldInfo[] infos = questionType.GetFields();
foreach (FieldInfo info in infos)
{
if (!info.IsPublic || !info.IsStatic)
continue;
string str = string.Empty;
object[] desc = info.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (desc == null || desc.Length == 0)
str = string.Empty;
else
{
System.ComponentModel.DescriptionAttribute a = desc[0] as System.ComponentModel.DescriptionAttribute;
if (a != null)
{
str = a.Description;
}
}
DataRow dr = dt.NewRow();
dr["ID"] = (int)info.GetValue(null);
dr["Name"] = str;
dt.Rows.Add(dr);
}
return dt;
}
用这个方法就得到了数据源,然后自己写代码绑定就好了。
public enum QuestionType
{
[Description("单选题")]
SingleChoice=0,
[Description("多选题")]
MultiChoices=1,
//[Description("填空题")]
//FillBlank = 2,
[Description("表格题")]
Table=3,
[Description("单选填空题")]
SingleBlank = 4,
[Description("问答题")]
AskAndAnswer = 5
}
要将起作为一个数据源,绑定到一个combox下拉框中.
处理方法如下:
public static DataTable GetQuestionTypeFromEnum()
{
DataTable dt = new DataTable("QuestionType");
dt.Columns.Add(new DataColumn("ID", typeof(System.Int16)));
dt.Columns.Add(new DataColumn("Name", typeof(System.String)));
Type questionType = typeof(Enum.QuestionType);
System.Reflection.FieldInfo[] infos = questionType.GetFields();
foreach (FieldInfo info in infos)
{
if (!info.IsPublic || !info.IsStatic)
continue;
string str = string.Empty;
object[] desc = info.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (desc == null || desc.Length == 0)
str = string.Empty;
else
{
System.ComponentModel.DescriptionAttribute a = desc[0] as System.ComponentModel.DescriptionAttribute;
if (a != null)
{
str = a.Description;
}
}
DataRow dr = dt.NewRow();
dr["ID"] = (int)info.GetValue(null);
dr["Name"] = str;
dt.Rows.Add(dr);
}
return dt;
}
用这个方法就得到了数据源,然后自己写代码绑定就好了。
From:一号门
Previous:别了2008
COMMENTS