Winforms DataGridView databind to complex type / nested property

前端 未结 4 1633
余生分开走
余生分开走 2020-12-03 14:52

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

MyClass.SubClass.Property

相关标签:
4条回答
  • 2020-12-03 15:07

    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;}
       }   
    }
    
    0 讨论(0)
  • 2020-12-03 15:11

    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.

    0 讨论(0)
  • 2020-12-03 15:12

    You can use Linq too!

    Get your generic list and use .select for choose the fields like the exemple below:

     var list = (your generic list).Select(i => new { i.idnfe, i.ide.cnf }).ToArray(); 
    
     if (list .Length > 0) {
          grid1.AutoGenerateColumns = false;
          grid1.ColumnCount = 2;
    
          grid1.Columns[0].Name = "Id";
          grid1.Columns[0].DataPropertyName = "idnfe";
          grid1.Columns[1].Name = "NumNfe";
          grid1.Columns[1].DataPropertyName = "cnf";
    
          grid1.DataSource = lista;
          grid1.Refresh();
    
    }
    
    0 讨论(0)
  • 2020-12-03 15:27

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

    One solution is to use this ObjectBindingSource as a Datasource.

    0 讨论(0)
提交回复
热议问题