简体   繁体   中英

How to populate a dataGridView with an IQueryable

I've added required columns and with right DataPropertyName s and I use following code to populate a datagridview. However, my dataGridView Shows columnheaders and one empty row only. What is wrong with my code?

public static IQueryable<Kolon> kolonlistele()
{
    using (Pehlivan.pehkEntities ctx = new Pehlivan.pehkEntities())
    {
        var result = from k in ctx.Kolons
                     select k;

        return result;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.DataSource = veritabani_islemleri.kolonlistele();
}

The problem here is delayed execution. result isn't actually a result. It's not the results of the query, it's just the query itself. That's what an IQueryable is. You can think of it as just a complex version of the SQL query, rather than the result set. The actual query won't be executed until you iterated over it or use some method that does iterate over it. (For example calling ToList , putting it in a foreach , or as is the case here, binding it to a DataGridView ).

This delayed execution is particularly problematic here because there is a disposable resource involved. You aren't actually executing the query until you're outside of the using block, which means that the DataSource has been disposed by the time you actually are trying to execute the query.

One way to solve this problem would be to just eagerly execute the query:

public static IQueryable<Kolon> kolonlistele()
{
    using (Pehlivan.pehkEntities ctx = new Pehlivan.pehkEntities())
    {
        return ctx.Kolons.ToList();
    }
}

By calling ToList inside of the using the query is executed before the data source is disposed. Also note I removed the from k in ctx.Kolons select k because it's not actually accomplishing anything; it's entirely redundant.

Your other option would be to increase the scope of the data source. If, instead of declaring it inside of the kolonlistele method the data source was declared at a "higher scope" such that the data source was set while the object was not yet disposed then it would also work. This would be more appropriate in situations where the data source is more expensive to create, or when the size of the query is so large that it's important to stream it (if you need to stream the data then eagerly evaluating it into a List would be a problem).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM