如果我有两个对象,即Fruit' and
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; }
}
如何绑定(bind) Fruit
的集合 (e.g. 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:
我找到了类似的帖子 here在 SO 上尝试了一些关于该帖子的建议,但它没有用......
最佳答案
您有多种选择。
您可以覆盖 ToString
Color
中的方法类返回Name
喜欢:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
或者不分配 List<Fruit>
作为DataSource
您可以选择匿名对象列表并选择 Name
的 Color
在你的结果中:
var result = yourListOfFruit
.Select(r => new
{
FruitID = r.FruitId,
Name = r.Name,
Color = r.Color.Name,
}).ToList();
dataGridView1.DataSource = result;
关于c# - 如何将对象集合绑定(bind)到 Winforms 中的 DataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26491961/