简体   繁体   English

将类列表绑定到DataGridView

[英]Bind List of Classes into DataGridView

I need to bind a List<MyClass> myList to a DataGridView . 我需要将List<MyClass> myListDataGridView And get in the results table with two columns ID and Name. 并在结果表中获得两列ID和Name。

Code snippets: 代码段:

private List<MyClass> myList = new List<MyClass>(){...};

public void BindClass()
{
    dataGridView.DataSource = myList;
}

public MyClass
{
   public MyDataClass Data{ get; set; }
}

public MyDataClass
{
   public string ID { get; set; }
   public string Name { get; set; }
}

Is it possible? 可能吗?

How about binding to an anonymous type: 如何绑定到匿名类型:

public void BindClass() 
{
    dataGridView1.DataSource = myList.Select(myClass => new {myClass.Data.ID, myClass.Data.Name}).ToList();
}

Will you be updating the data in the datagridview ? 您将更新datagridview中的数据吗?

To do that without changing the model is exceptionally tricky (but possible), requiring ICustomTypeDescriptor or TypeDescriptionProvider , and a custom PropertyDescriptor . 在不更改模型的情况下做到这一点非常棘手(但可行),需要ICustomTypeDescriptorTypeDescriptionProvider以及自定义PropertyDescriptor To be honest: not worth it. 老实说:不值得。

Just add pass-thru properties: 只需添加直通属性:

public MyClass
{
   public MyDataClass Data{get; set;}
   [DisplayName("ID")]
   public string DataID {
     get {return Data.ID;}
     set {Data.ID = value;}
   }
   [DisplayName("Name")]
   public string DataName {
     get {return Data.Name;}
     set {Data.Name = value;}
   }
}

It's easy with LINQ as you can see in This answer 如您在此答案中所见,使用LINQ很容易

Here's a simple implementation of something I needed to attach to datagridview. 这是我需要附加到datagridview的东西的简单实现。

     DataGridView1.DataSource =  _
(From i In ItemList Select i.ListID, i.FullName, i.PurchaseDesc, i.EditSequence).ToList

No, you can't do this out of the box. 不,您不能开箱即用。 You will have to write a custom binding source (most likely with specialized logic for your specific purpose) to allow 'drilling' deeper than just 1 level of properties. 您将必须编写一个自定义绑定源(很可能具有用于特定目的的专用逻辑),以允许“钻取”的深度不止1级属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM