加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何将对象集合绑定到Winforms中的DataGridView

发布时间:2020-12-16 02:03:36 所属栏目:百科 来源:网络整理
导读:如果我有两个对象,即Fruit’和Color`,它们的定义如下: public class Fruit { public int FruitId { get; set; } public string Name { get; set; } public Color Color { get; set; } } public class Color { public int ColorId { get; set; } public stri
如果我有两个对象,即Fruit’和Color`,它们的定义如下:

public class Fruit  
{  
  public int FruitId { get; set; }  
  public string Name { get; set; }  
  public Color Color { get; set; }  
}  

public class Color  
{  
  public int ColorId { get; set; }  
  public string Name { get; set; }  
}

如何将Fruit的集合(例如List< Fruit>)绑定到DataGridView?结果输出将类似于以下内容:

+-----+--------+----------+  
| Id  | Name   | Color    |  
+-----+--------+----------+  
| 10  | Apple  | Red      |  
| 20  | Orange | Orange   |  
| 30  | Grapes | Violet   |  
+-----+--------+----------+

而不是像下面的输出:(注意:N.Color中的N表示对象Color的命名空间)

+-----+--------+------------+  
| Id  | Name   | Color      |  
+-----+--------+------------+  
| 10  | Apple  | N.Color    |  
| 20  | Orange | N.Color    |  
| 30  | Grapes | N.Color    |  
+-----+--------+------------+

更新#1:
我在SO上发现了一个类似的帖子here,并在该帖子上尝试了一些建议,但它不起作用……

解决方法

你有多种选择.

您可以在Color类中重写ToString方法以返回Name,如:

public class Color
{
    public int ColorId { get; set; }
    public string Name { get; set; }
    public override string ToString()
    {
        return Name;
    }
}

或者代替分配List< Fruit>作为DataSource,您可以选择匿名对象列表,并在结果中选择“颜色名称”,如:

var result = yourListOfFruit
                .Select(r => new
                        {
                            FruitID = r.FruitId,Name = r.Name,Color = r.Color.Name,}).ToList();

dataGridView1.DataSource = result;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读