Search code examples
c#data-binding

C# Tutorial - Binding a DataGridView to a Collection which contains an object


So I have a datagridview.

Normally I can create a bindinglist of my object and it will display all the data and colums correctly

E.g

BindingList<Customer> CustomerList = new BindingList<Customer>();
myDataGridView.DataSource = CustomerList;

And it will display a column for each property in Customer which has a getter. It will also display a row for each object.

Perfect result.

Now in my current scenario, I have these objects:

public class Reservedele
{
    public int Rnr { get; private set;}
    public string Navn { get; private set;}
    public double Pris { get; private set;}
    public string Type { get; private set;}

    public Reservedele(int rnr, string navn, double pris, string type)
    {
        Rnr = rnr;
        Navn = navn;
        Pris = pris;
        Type = type;
    }
}
public class IndkøbsKurvReservedele
{
    public Reservedele Reservedel  { get; private set;}
    public int Antal { get; private set; }
    public double Pris { get; private set; }

    public IndkøbsKurvReservedele(Reservedele reservedel, int antal, double pris)
    {
        Reservedel = reservedel;
        Antal = antal;
        Pris = pris;
    }
}

So if I do this:

BindingList<IndkøbsKurvReservedele> ReserveDeleListeIndKøbsKurv = new BindingList<IndkøbsKurvReservedele>();
myDataGridView.DataSource = ReserveDeleListeIndKøbsKurv;

It won't work :( The error is that the datagridview shows:

  • The object itself
  • Antal
  • Pris

Example: alt text

How can I instruct the datagridview that I want it to have the properties from Reservedel followed by the properties in IndkøbsKurvReservedele as headers??

For reference, Reservedel means "spare parts" and IndkøbsKurvReservedel means something like "ShoppingBasketOfSpareParts". Antal means "amount" as in how many there is. Sorry for the foreign variable naming.

EDIT: I have another question: How can I make the Rnr property not to show up as a column?


Solution

  • This is my solution:

    public class IndkøbsKurvReservedele
    {
        //public Reservedele Reservedel  { get; private set;}
        private int Rnr;
        public string Navn { get; private set; }
        public double Pris { get; private set; }
        public string Type { get; private set; }
        public int Antal { get; private set; }
        public double SPris { get; private set; }
    
        public IndkøbsKurvReservedele(Reservedele reservedel, int antal, double sPris)
        {
            Rnr = reservedel.Rnr;
            Navn = reservedel.Navn;
            Pris = reservedel.Pris;
            Type = reservedel.Type;
            Antal = antal;
            SPris = sPris;
        }
        public int HenrReservedelsNummer()
        {
            return Rnr;
        }
    }
    

    If anyone creates a better. I will accept theirs instead.