Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms DataGridView databind to complex type / nested property

I am trying to databind a DataGridView to a list that contains a class with the following structure:

MyClass.SubClass.Property

When I step through the code, the SubClass is never requested.

I don't get any errors, just don't see any data.

Note that I can databind in an edit form with the same hierarchy.

like image 810
B Z Avatar asked Mar 25 '09 22:03

B Z


3 Answers

Law of Demeter.

Create a property on MyClass that exposes the SubClass.Property. Like so:

public class MyClass
{
   private SubClass _mySubClass;

   public MyClass(SubClass subClass)
   {
      _mySubClass = subClass;
   }

   public PropertyType Property
   {
      get { return _subClass.Property;}
   }   
}
like image 155
Chris Holmes Avatar answered Nov 20 '22 14:11

Chris Holmes


You can add a handler to DataBindingComplete event and fill the nested types there. Something like this:

in form_load:

dataGridView.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView_DataBindingComplete);

later in the code:

void dataGridView_DataBindingComplete(object sender,
        DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView.Rows)
    {
        string consumerName = null;
        consumerName = ((Operations.Anomaly)row.DataBoundItem).Consumer.Name;
        row.Cells["Name"].Value = consumerName;
    }
}

It isn't nice but works.

like image 4
vizmi Avatar answered Nov 20 '22 12:11

vizmi


You can't bind a DataGridView to nested properties. It's not allowed.

One solution is to use this ObjectBindingSource as a Datasource.

like image 3
gcores Avatar answered Nov 20 '22 14:11

gcores