c# - 如何将对象集合绑定(bind)到 Winforms 中的 DataGridView

标签 c# winforms mvp architectural-patterns

如果我有两个对象,即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您可以选择匿名对象列表并选择 NameColor在你的结果中:

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/

相关文章:

c# - UWP:绑定(bind)到 View 模型属性

c# - 如何忽略服务器端的 EntityValidationErrors

c# - 如何使用方法 async Task<string> 并返回字符串,然后如何将该方法的委托(delegate)传递给构造函数并在以后使用它?

java - Model-View-Presenter被动 View : bootstraping - who displays the view initially?

asp.net - 使用模型 View 演示者设计模式的安全性和角色授权

c# - 在pdf c#中的另一个图像上添加图像水印

c# - 在类级别定义的 private const 然后在属性上使用,为什么会编译?

.net - 如何找出线程锁发生的位置?

c# - 如何正确显示重叠的用户控件?

c# - mvp 模式中的(嵌套)用户控件导致偶发问题