Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data binding linq query to datagridView in Entity Framework 5.0

I am learning the Entity Framework (5.0 and VSExpress 2012) and I'm having real trouble binding my query to a dataGridView in WinForms. I have the below code and it displays my query okay when I start the application but I don't know what I need to do to update the dataGridView after changing the data in the underlying database. What's the best way of doing this? What am I doing wrong here?

private void Form1_Load(object sender, EventArgs e)
    {
        using( var ctx = new TimeKeepEntities())
        {

            var qLoggedIn = from r in ctx.tblTimeRecords
                        where (r.tblEmployee.Active && !r.ClockOut.HasValue) || System.Data.Objects.EntityFunctions.DiffDays(r.ClockOut, DateTime.Now)<30
                        select new { Name = r.tblEmployee.Last + ", " + r.tblEmployee.First, r.tblProject.ProjName, r.ClockIn, r.ClockOut };

            dataGridView1.DataSource = qLoggedIn.ToList();

        }
    }
like image 806
Mr1159pm Avatar asked Sep 19 '12 19:09

Mr1159pm


1 Answers

Pho please note that they are using winforms not asp.net. According to MSDN you can do the following:

BindingSource bindingSource1 = new BindingSource();
bindingSource1.DataSource = (from r in ctx.tblTimeRecords
                        where (r.tblEmployee.Active && !r.ClockOut.HasValue) || System.Data.Objects.EntityFunctions.DiffDays(r.ClockOut, DateTime.Now)<30
                        select new { Name = r.tblEmployee.Last + ", " + r.tblEmployee.First, r.tblProject.ProjName, r.ClockIn, r.ClockOut }).ToList();

dataGridView1.DataSource = bindingSource1;

see: msdn documentation

like image 103
Lance Avatar answered Oct 02 '22 00:10

Lance