Asım Gündüz
Asım Gündüz

Reputation: 1297

How to display master related data in C# gridview using Entity Framework

I'm using Entity Framework and stuck on displaying the detailed records of the master table.

I have a MasterBindingSource and DetailsBindingSource along with two DataGridViews on the form.

What I'm trying to do is: fill the detailsGridView related to the selected data on the masterGridView.

Can anyone guide me through this please?

This is what I've done, I'm able to fill the masterGridview but details table are not filled related to the master...

MasterTbBindingSource.DataSource = lobo.MasterTb.Include("DetailTb").ToList();

What am I missing? Thanks

UPDATE

public partial class CONTACTS_BASE//Master
{
    public CONTACTS_BASE()
    {
        this.ORDERS = new HashSet<ORDER>();
    }

    public int CB_REFNO { get; set; }
    public string CB_NAME { get; set; }
    public string CB_ID_NO { get; set; }
    public string CB_AGE { get; set; }

    public virtual ICollection<ORDER> ORDERS { get; set; }
}

public partial class ORDER //Detail
{
    public int OR_REFNO { get; set; }
    public string OR_PROD_CODE { get; set; }
    public Nullable<int> OR_M_REFNO { get; set; }

    public virtual CONTACTS_BASE CONTACTS_BASE { get; set; }
}

and this is what I tried to achive my goal:

using (var lobo = new MyEfTestEntities())
{
            CONTACTS_BASEBindingSource.DataSource = lobo.CONTACTS_BASE.Include("ORDERS").ToList();

            ORDERBindingSource.DataSource = CONTACTS_BASEBindingSource;
            ORDERBindingSource.DataMember = "ORDERS";  
}

Upvotes: 1

Views: 1150

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205779

It's unrelated to Entity Framework. Automatic Master - Details synchronization of two DataGridView controls with BindingSource components is quite easy. All you need is to set the master BindingSource as DataSource of the detail BindingSource and use the DataMember of the detail BindingSource to specify the name of the detail collection.

Something like this:

MasterTbBindingSource.DataSource = lobo.MasterTb.Include("DetailTb").ToList();
DetailsBindingSource.DataSource = MasterTbBindingSource;
DetailsBindingSource.DataMember = "DetailTb";  

Upvotes: 2

Related Questions