简体   繁体   中英

Binding Complex Data source of a class into Grid View

Here I have these Classes:

public class CustomerDebt
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public string Remain { get; set; }
    public List<Shops> details = new List<Shops>();
}

public class Shops
{
    public List<int> ints = new List<int>();
    public List<string> strings = new List<string>();
}

I'm making a list of CustomerDebts objects:

List<CustomerDebt> debts = new List<CustomerDebt>();

and Here I will add one item to it:

Shops shop = new Shops();
shop.ints.Add(1);
shop.ints.Add(2);

shop.strings.Add("M");
shop.strings.Add("S");
shop.strings.Add("F");

CustomerDebt d = new CustomerDebt();

d.ID = 12;
d.Name = "Joe";
d.Family = "Steven";
d.Remain = "1000";
d.details.Add(shop);

debts.Add(d);

Now I bind debts list into a grid view:

gridview.DataSource = debts;

It will automatically fill the grid view with only "ID,Name,Family,Remain" properties of CustomerDebt Class. But I need to bind the List property which is a list of another Class into grid view.

I think it needs something like {get; set;} to be shown in grid, But also I do not know If the grid can show a nested class like this.

Hope I'm clear. What should I do to get a clean Grid view with such list of Class objects?

There is no built-in support for Master Details in the DataGridView Control in Windows Forms. But we have the option to use Third Party Libraries Like:


As for the binding issue, yes you need to have a public property with a public getter:

public List<Shops> details { set; get; } = new List<Shops>();

For prior to C# 6 you can use:

public class CustomerDebt
{
    public CustomerDebt()
    {
       details = new List<Shops>();
    }

    public List<Shops> details { set; get; }
}

Another way of doing this other than the accepted answer can be like below. Columns can be added manually and then the rows can be filled accordingly.

        this.gridview.Columns.Add("ID", "ID");
        this.gridview.Columns.Add("Name", "Name");
        this.gridview.Columns.Add("Family", "Family");
        this.gridview.Columns.Add("Remain", "Remain");
        this.gridview.Columns.Add("Details", "Details");

        foreach (var debt in debts)
           foreach (var detail in debt.details)
               this.dataGridView1.Rows.Add(debt.ID, debt.Name, debt.Family, debt.Remain, "Ints:" + string.Join(",", detail.ints) + "   Strings:" + string.Join(",", detail.strings));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM