How to bind a collection of objects to a DataGridView in Winforms

devpro101 picture devpro101 · Oct 21, 2014 · Viewed 15.7k times · Source

If i have two objects, namely Fruit' andColor` and their definitions are as follows:

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; }  
}  

How do I bind a collection of Fruit (e.g. List<Fruit>) to a DataGridView? where the resulting output would be something similar to the following:

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

and NOT like the following output below: (Note: the N in N.Color indicates the namespace of the object Color)

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

Update #1:
I found a similar post here on SO and tried some of the suggestion on that post but it's not working...

Answer

Habib picture Habib · Oct 21, 2014

You have multiple options.

You can override ToString method in your Color class to return Name like:

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

Or instead of assigningList<Fruit> as DataSource you can select a list of anonymous object and select Name of Color in your result like:

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

dataGridView1.DataSource = result;