Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView - Use DataPropertyName to show child element property

Lets image that I have the following classes

public class Master
{
    public string MasterName = "Something";

    public List<Detail> details = new List<Detail>();
}

public class Detail 
{
    public string Foo = "Test";
}

And then I want to show the collection of Details objects in a DataGridView, using the code below

DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Details.Foo";
column.HeaderText = "Foo header";

dgv.Columns.Add(column);

The column is shown in the grid, but without value

like image 294
Andrey Avatar asked Dec 26 '12 22:12

Andrey


Video Answer


1 Answers

Just do this:

Mask the property you want to get a childvalue from with [Browsable(false)] so it wont show up in the datagrid. Then create a NEW property in your class that holds the child object which has only a "get" method showing the childproperty value: For example:

[Browsable(false)] //Because we use the CreatorUsernameProperty to do this.
public virtual User Creator { get; set; }

[DisplayName("Creator")] //shows like this in the grid
public string CreatorUsername => Creator?.Username;
like image 146
Jal Avatar answered Oct 06 '22 11:10

Jal