Entity Framework DataGridView binding source

c# datagridview entity-framework-6


I am discovering Entity Framework, I have a winforms project and a database running on SQLserver which has 2 Tables: Student and Standard. First I created a ADO.NET Entity Data Model from the database with the wizard help thing. Then I have a DataGridView control which has a bindingsource as DataSource. The DataGridView is correctly populated with the fields from Student table BUT what i'd like to do is add a column to the same DataGridView but with data coming from the Standard table. Take a look at the picture : enter image description here

I'm stuck here i don't know how to do this.

7/12/2015 11:43:45 PM

Accepted Answer

You should be able to do something like this:

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 Load() or OnClick():

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";

Or you can manually add these into the designer.

7/13/2015 2:52:07 PM

Related Questions


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