Load data asynchronously into DataTable in Windows Forms

后端 未结 1 1070
温柔的废话
温柔的废话 2020-12-06 15:52

I\'m modifying the data access layer of an old WinForms/ADO app to get Salesforce objects using soql over the asynchronous developerforce rest api. The following approach

相关标签:
1条回答
  • 2020-12-06 16:16

    You can have an async method which returns Task<DataTable> and then in async form Load event handler or in the async method which you want to perform data-binding, await call it, then use the result to bind to the grid.

    Example

    public async Task<DataTable> GetDataAsync(string command, string connection)
    {
        var dt = new DataTable();
        using (var da = new SqlDataAdapter(command, connection))
            await Task.Run(() => da.Fill(dt));
        return dt;
    }
    
    private async void Form1_Load(object sender, EventArgs e)
    {
        var command = @"SELECT * FROM Category";
        var connection = @"Your Connection String";
        var data = await GetDataAsync(command, connection);
        this.dataGridView1.DataSource = data;
    }
    

    To see how you can show a loading animation over the DataGridView, take a look at this post.

    0 讨论(0)
提交回复
热议问题