CleverWolf
CleverWolf

Reputation: 73

Is there a way for reading data asynchronously for datagridview in c#?

i am trying to fill datagridview datasourece asynchronously in entity framework, but it shows me cross-thread error and it does not work, does anybody know how? thank you very much

 private async Task FillData()
    {
        await Task.Run(() =>
        {
            Model.AsyncTestDBEntities db = new Model.AsyncTestDBEntities();
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = db.Table_1.ToList();
        });
    }

when i call the above method it does not work

  private async void button1_Click(object sender, EventArgs e)
    {
        await FillData();
    }

Upvotes: 0

Views: 292

Answers (1)

John Wu
John Wu

Reputation: 52280

Use ToListAsync instead of Task.Run().

private async Task FillData()
{
    var db = new Model.AsyncTestDBEntities();
    var list = await db.Table_1.ToListAsync();
    dataGridView1.AutoGenerateColumns = false;
    dataGridView1.DataSource = list;
}

Upvotes: 2

Related Questions