Intellisense for DataGridView column names when using a List<T> as the Datasource
I have a DataGridView that has 4 columns that need to be formatted. The dataSource for this DataGridView is a generic list of objects from a class with 4 properties.
At design time, how can I use intelisense to specify the column?
DataGridView dgv = new DataGridView();
List<MyDataRow> myDataList = new List<MyDataRow>();
// List is populated in this section of code...
dgv.DataSource = myDataList;
dgv.Columns["ALongDescriptiveNameThatCouldEasilyBeMistyped"开发者_JAVA技巧].Width = 80; .
// dgv is added to a form and displayed in this section of code
public class MyDataRow
{
public string FirstName { get; set; }
public string LastName { get; set; }
public double ALongDescriptiveNameThatCouldEasilyBeMistyped { get; set; }
public int YearsOfService { get; set; }
public int MonthsOfService { get; set; }
}
You could use the following class which contains a method using an expression tree as an argument to determine a member name based on a lambda expression:
public class MemberHelper<T> where T : class
{
public string GetName<U>(Expression<Func<T, U>> expression)
{
MemberExpression memberExpression = expression.Body as MemberExpression;
if(memberExpression != null)
return memberExpression.Member.Name;
throw new InvalidOperationException("Member expression expected");
}
}
You can use the method like so:
MemberHelper<MyDataRow> memberHelper = new MemberHelper<MyDataRow>();
dgv.Columns[memberHelper.GetName(d => d.FirstName)].Width = 80;
Intellisense will not help, because Columns is just int/string indexer. You can use attributes on properties and some reflection and then Linq query constructing string array containing names of properties decorated with specific attribute, but maybe it's not worth it in your case.
The easiest way is to declare enumeration which contains your column names with assigned integer values from 0 to N , and use that enum for Index based access to the columns of DataGrid.
Something like this pseudocode:
enum ColumnNames
{
ColumnName1 = 0,
ColumnName2 = 1,
ColumnName3 = 2,
.....
.....
}
精彩评论