First of all, I usually write very little about a set of items on the interface, especially the Xiami dview, so each time I display the data, I directly call it like this:
This. Datagridview1.datasource =This. Entitylist; // entitylist = List <entity>
In this case, there is no problem with writing Xiami, but the requirements of customers are getting higher and higher. For example, Xiami needs to use a uniform style and Chinese characters .. in this case, the problem arises, because in the specified datagridview. when datasource is used, the column name is bound to the property name of the item of the collection object by default, that is:
Typeof(Tentity). getproperty ("Name"). Name;
In general, this name must be in e-text. I believe that it is impossible to use Chinese for attributes this year.
What's more, when Orm is prevalent today, the set of IDs in the database will naturally be reflected in the Entity class. Then, when binding the datasource attribute of a dview, show all IDs on the interface. Isn't it too unprofessional?
So, what if the column name is Chinese and the specified column is dynamically displayed?
Step 1: first inherit a class from attribute. My name is 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 ;}
}
}
Step 2: Specify the attribute of the column to be displayed in the datagridview, that is, the attribute of the object class.
Step 3: Call this method before specifying 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;
}
}
}
So, roughlyCodeIt will look like this:
This. Parse<Tentity>(This. Datagridview1 );
//Tentitylist is list <tentity>;
This. Datagridview1.datasource= This. Tentitylist;
Of course, you must first set datagridview1.autogeneratecolumn = false;
Specify columnvisibleattribute for the corresponding attribute.