Entity Framework DataGridView binding source

c# datagridview entity-framework-6

Question

I'm learning Entity Framework. I have a winforms project and a SQLserver database with two tables:Student and Standard . Using the wizard help feature, I first constructed an ADO.NET Entity Data Model from the database. Following that, I have a DataGridView control with a bindingsource set as the DataSource. The fields from the DataGridView are correctly filled in.Student table However, I'd like to add a column to the same DataGridView that contains information from theStandard table. Look at the illustration:enter image description here

I'm helpless since I have no idea how to proceed.

1
1
7/12/2015 11:43:45 PM

Accepted Answer

You ought to be able to carry out the following:

public class DataBindingProjection
{
    public string StudentName { get; set; }
    public date DateOfBirth { get; set; }
    public string Height { get; set; }
    public string Weight { get; set; }
    ... etc.
    public string StandardName { get; set; 
}

In your OnClick() or Load() method

var query = context.Students
                   .Include(s => s.Standard)
                   .Select(s => new DataBindingProjection
                    {
                       StudentName = s.StudentName,
                       DateOfBirth = s.DateOfBirth,
                       Height = s.Height,
                       Weight = s.Weight,
                       ...
                       StandardName = s.Standard.StandardName
                    };

dataGridView1.DataSource = query.ToList();
dataGridView1.Columns[1].DataPropertyName = "StudentName";
dataGridView1.Columns[2].DataPropertyName = "DateOfBirth";
dataGridView1.Columns[3].DataPropertyName = "Height";
dataGridView1.Columns[4].DataPropertyName = "Weight";
dataGridView1.Columns[5].DataPropertyName = "StandardName";

Alternatively, you might manually add these to the designer.

2
7/13/2015 2:52:07 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow