原来一直使用Enum,但是总是感觉不好用,而且不支持数字开头,特殊字符也不能用,采用数据库表又感觉不方便,而且影响速度,后来想到一个办法,使用本地临时构造DataTable的办法,当需要的时候就构造相应的类就可以返回所需的表了,特别对哪些能构使用数据源的控件特别方便,如果是WINFORM中,可以做成DLL,同样方便,对于一些特殊情况,还可以在相应的类中添加自己的功能。
public class EnumBase
{
DataTable dt = new DataTable();
public EnumBase()
{
dt.Columns.Add("ID",typeof(System.Int32));
dt.Columns.Add("Name",typeof(System.String));
dt.PrimaryKey = new DataColumn[]{dt.Columns["ID"]};
}
/// <summary>
/// 返回和设置表
/// </summary>
public DataTable GetDataTable
{
get{return dt;}
set{dt = value;}
}
/// <summary>
/// 返回类型名称
/// </summary>
/// <param name="m_ID"></param>
/// <returns>编号</returns>
public string strName(string m_ID)
{
DataRow dr = dt.Rows.Find(m_ID);
if(dr == null)
return null;
else
return dr["Name"].ToString();
}
/// <summary>
/// 返回类型编号
/// </summary>
/// <param name="m_Name"></param>
/// <returns>名称</returns>
public string strID(string m_Name)
{
DataView dv = new DataView(dt);
dv.RowFilter = "Name='" + m_Name + "'";
if(dv.Count >0)
{
return dv[0]["ID"].ToString();
}
else
{
return null;
}
}
}
public class ReportType:EnumBase
{
public ReportType()
{
DataTable dt = base.GetDataTable;
#region 文章等级
DataRow dr1 = dt.NewRow();
dr1["ID"] = "1";
dr1["Name"] = "★";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["ID"] = "2";
dr2["Name"] = "★★";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["ID"] = "3";
dr3["Name"] = "★★★";
dt.Rows.Add(dr3);
#endregion
base.GetDataTable = dt;
}
}
public class IssueArticleType:EnumBase
{
public IssueArticleType()
{
DataTable dt = base.GetDataTable;
#region 文章类型
DataRow dr1 = dt.NewRow();
dr1["ID"] = "0";
dr1["Name"] = "综合信息";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["ID"] = "1";
dr2["Name"] = "报表统计与分析";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["ID"] = "2";
dr3["Name"] = "经验交流";
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4["ID"] = "3";
dr4["Name"] = "事故通报";
dt.Rows.Add(dr4);
#endregion
base.GetDataTable = dt;
}
}
使用很简单:
this.comboBox1.DataSource = new IssueArticleType().GetDataTable;
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "ID";
id = Convert.ToInt32(this.comboBox1.SelectedValue);
text = this.comboBox1.Text;
id = new IssueArticleType().strID("综合信息");
text = new IssueArticleType().strName("1");