Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Winforms DataGridView数据绑定到复杂类型/嵌套属性_C#_.net_Data Binding_Datagridview_.net 3.5 - Fatal编程技术网

C# Winforms DataGridView数据绑定到复杂类型/嵌套属性

C# Winforms DataGridView数据绑定到复杂类型/嵌套属性,c#,.net,data-binding,datagridview,.net-3.5,C#,.net,Data Binding,Datagridview,.net 3.5,我正在尝试将DataGridView数据绑定到包含具有以下结构的类的列表: MyClass.SubClass.Property 当我单步执行代码时,从未请求子类 我没有收到任何错误,只是看不到任何数据 请注意,我可以在具有相同层次结构的编辑表单中进行数据绑定。您不能将DataGridView绑定到嵌套属性。这是不允许的 一种解决方案是将其用作数据源。 在MyClass上创建一个属性,该属性公开子类.property。像这样: public class MyClass { private

我正在尝试将
DataGridView
数据绑定到包含具有以下结构的类的列表:

MyClass.SubClass.Property
当我单步执行代码时,从未请求
子类

我没有收到任何错误,只是看不到任何数据


请注意,我可以在具有相同层次结构的编辑表单中进行数据绑定。

您不能将DataGridView绑定到嵌套属性。这是不允许的

一种解决方案是将其用作数据源。

在MyClass上创建一个属性,该属性公开子类.property。像这样:

public class MyClass
{
   private SubClass _mySubClass;

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

   public PropertyType Property
   {
      get { return _subClass.Property;}
   }   
}

您可以向DataBindingComplete事件添加处理程序,并在其中填充嵌套类型。 大概是这样的:

以表格形式加载:

dataGridView.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView_DataBindingComplete);
代码后面部分:

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;
    }
}
它不好,但很有效。

你也可以使用Linq

获取您的通用列表并使用。选择以选择如下示例所示的字段:

 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();

}

是的,这是我的最后一个病例场景,但我有7个亚型需要处理,所以我在寻找更好的方法。Thx提示。@BZ这可能比在数据绑定之前将所有项目强制转换为子类型要快。