user3813360
user3813360

Reputation: 586

Entity Framework DataGridView binding source

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.

Upvotes: 1

Views: 5768

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

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.

Upvotes: 3

Related Questions