Reputation: 139
UPD: I have found this article: http://www.developer-corner.com/blog/2007/07/19/datagridview-how-to-bind-nested-objects/ , but it is pretty old, posted in 2007.
I have C# win forms app and I want to show list of items in datagridView: here is the List: `
public static List<Item> ItemsList { get; set; } = new List<Item>()
{
new Item()
{
Id = 1,
ItemName = "Ice Tea",
ItemCategory = new Category(){
Name = "Drinks"
},
Price = 4000.00,
},...}`
as you can see I have another object ItemCategory inside Item. Here is the code to connect to dataGrid:
dataGridAllProducts.DataSource = Item.ItemsList;
The problem is that I cannot get the Name from ItemsList and show in rows, here is what it shows in output:
As you can see instead of Drinks it shows another thing. Also i tried to loop through my list using foreach and rows to datagrid but it throwed some errors .
Upvotes: 0
Views: 1116
Reputation: 1054
On class Category add this code:
public override string ToString(){
return this.Name;
}
When you call the object on need a string, the object Category show Name property.
Upvotes: 1
Reputation: 879
The column binding for the data grid view might not be right. Please try the following in the design view: 1. Right click on your data grid view and select "Edit Columns" 2. Select the column for which the data is not coming right. 3. In the "DataPropertyName" under "Data" mention "Name" i.e. the property name of your Item class.
Upvotes: 0