5

如果我有两个对象,即Fruit' andColor ,它们的定义如下:

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 (e.g. List<Fruit>)到 DataGridView?结果输出将类似于以下内容:

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

并且不喜欢下面的输出:(注意:NN.Color表示对象颜色的命名空间)

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

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

4

3 回答 3

6

您有多种选择。

您可以覆盖类中ToString的方法Color以返回Name如下:

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

或者,您可以选择匿名对象列表并在结果中选择,而不是分配List<Fruit>,例如:DataSourceNameColor

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

dataGridView1.DataSource = result;
于 2014-10-21T17:02:22.350 回答
5

好的,在弄清楚如何使我的应用程序工作几天后,我设法找到了一些对解决我的问题有很大帮助的文章。我想我会在这里为你们分享它,所以让我们开始吧:

首先,假设我们已经有一个存储在变量 fruits 中的水果列表,并假设我们已经从一个方法中获得了它的值:

List<Fruit> fruits = method();  

现在,我的问题是......如果我使用以下命令将该列表绑定到 datagridview:

datagridview.DataSource = fruits;  

它会给我一个类似于以下的结果:

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

这不是我想要的。所以我想也许如果我以某种方式手动将每一列放到 datagridview 中,我可以指定我的水果列表中要显示的属性。所以我做了这样的事情:

DataGridViewColumn col3 = new DataGridViewTextBoxColumn();  
col3.DataPropertyName = "Color.Name";  
col3.HeaderText = "Color Name";  
dataGridView1.Columns.Add(col3);  

但是,在 DataGridView 列的 DataPropertyName 上指定这样Color.Name的内容不起作用,只会导致在 DataGridView 上没有数据显示的空白列。为了让它工作,DataGridView 应该有一个单元格格式化函数来正确显示它在给定列中的值。有关如何进行格式化的完整教程,您可以从Antonio Bello 的博客 中查看。

就是这样,希望对你也有帮助^_^

于 2014-10-23T07:18:35.100 回答
1

您可以检查此属性DataGridView.DataSource 属性

        // Automatically generate the DataGridView columns.
        dataGridView1.AutoGenerateColumns = true;

        // Set up the data source.
        bindingSource1.DataSource = GetData("Select * From Products");
于 2014-10-21T16:54:16.423 回答