DataGridView for a list of classes without accessors
I have a list of objects (List<MyClass>
) whose members I would like to have visible in a DataGridVi开发者_Go百科ew on a selective basis.
Here is my class:
class MyClass
{
public int X;
public int Y;
public int Z;
}
Is it possible to have just the X
and Y
members visible in the grid without the use of accessors? I tried adding columns to the DataGridView but the data wasn't being filled (but I could have been doing this wrong. I just created a column with the same name as the field).
I am binding the list to the control with the following code:
datagrid.DataSource = list;
Any help on this would be amazing.
The problem is with your class; you are having public members but not public properties. Bindable controls such as DataGridView bind with public properties with get; set;
In short you need to change your class
class MyClass
{
public int X
{
get;
set;
}
public int Y
{
get;
set;
}
public int Z
{
get;
set;
}
}
And then in designer specify column's DataPropertyName
to respectively
DataPropertyName = X
DataPropertyName = Y
DataPropertyName = Z
精彩评论