DataGridView动态显示指定列
首先要说明的是,我平时对界面上的一套东东写的很少,尤其是这个虾米DataGridView,所以每次显示数据时为了方便,直接这样调用:
this.dataGridView1.DataSource = this.entityList; //entityList = List<Entity>
这样写一般情况下没虾米问题,但现在的客户要求越来越高,诸如虾米要使用统一的样式啊,要使用中文啊等等..这样问题就来了,因为在指定DataGridView.DataSource时,列名会默认绑定到集合对象item的属性名,也就是:
typeof(Tentity).GetProperty("Name").Name;
并且一般情况下,这个Name肯定是e文的,我相信这年头用中文做属性应该是件impossible的事了吧 :)
而且,在ORM盛行的今天,数据库中的那一套id啊啥的,自然也会在实体类中体现出来,那么,在绑定一个DataGridView的DataSource属性时,把id都显示在界面上,是不是太不专业了?
so,要达到列名为中文,并且动态显示指定列的目的,怎么办?
第一步,先从Attribute继承个类吧,我叫它ColumnVisibleAttribute:
ColumnVisibleAttribute
[global::System.AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
public sealed class ColumnVisibleAttribute : Attribute
{
public ColumnVisibleAttribute(string custom)
: this(custom, true)
![]()
{ }
![]()
public ColumnVisibleAttribute(string customName, bool isDisplay)
![]()
{
this._customName = customName;
this._display = IsDisplay;
}
![]()
private bool _display;
public bool IsDisplay
![]()
{
get
{ return _display; }
set
{ _display = value; }
}
![]()
private string _customName;
public string CustomName
![]()
{
get
{ return _customName; }
set
{ _customName = value; }
}
}
第二步,给要在DataGridView中显示的列,也就是实体类的属性,指定该特性
第三步,在指定DataSource之前,调用该方法:
Parse
private void Parse<T>(DataGridView grid)
![]()
{
PropertyInfo[] proInfos = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
int colID;
for (int i = 0; i < proInfos.Length; i++)
![]()
{
PropertyInfo pi = proInfos[i];
if (pi.IsDefined(typeof(ColumnVisibleAttribute), false))
![]()
{
ColumnVisibleAttribute colVis = pi.GetCustomAttributes(typeof(ColumnVisibleAttribute), false)[0] as ColumnVisibleAttribute;
colID = grid.Columns.Add(pi.Name, colVis.CustomName);
grid.Columns[colID].DataPropertyName = pi.Name;
}
}
}
所以,大致代码会像这样:
this.Parse<Tentity>(this.dataGridView1);
//TentityList is List<Tentity>;
this.dataGridView1.DataSource = this.TentityList;
当然,需要先设置dataGridView1.AutoGenerateColumn = false;
那么,想显示哪几列,就给对应的属性指定ColumnVisibleAttribute吧 ;)





}
}