Bind (Populate) ASP.Net GridView asynchronously (Async Method) using C#

Last Reply one month ago By dharmendr

Posted one month ago

I have an article in which the author has explained to bind the data to gridview using asynchronous programming.

Using Async/Await Task Methods With SQL Queries .NET 4.5

But I am unable to bind it to just 1 simple gridview. But there is nothing happening to the page.

Please provide me the solution for this.

so far I have done this :

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BSD
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetSomeData("select * from app_notifications");
                GridView1.DataBind();
            }
        }

        private string connection = "Data Source=.;Initial Catalog=xxxx;Integrated Security=True;Pooling=false;";

        private async Task GetSomeData(string sql)
        {
            //Use Async method to get data
            DataSet results = await GetDataSetAsync(connection, sql, null);

            //Populate once data received
            GridView1.DataSource = results.Tables[0];
        }

        public Task<DataSet> GetDataSetAsync (string sConnectionString, string sSQL, params SqlParameter[] parameters)
        {
            return Task.Run(() =>
            {
                using (var newConnection = new SqlConnection(sConnectionString))
                using (var mySQLAdapter = new SqlDataAdapter(sSQL, newConnection))
                {
                    mySQLAdapter.SelectCommand.CommandType = CommandType.Text;
                    if (parameters != null) mySQLAdapter.SelectCommand.Parameters.AddRange(parameters);

                    DataSet myDataSet = new DataSet();
                    mySQLAdapter.Fill(myDataSet);
                    return myDataSet;
                }
            });
        }
    }
}
Posted one month ago Modified on 29 days ago

Hi EmadKhan,

You need to ensure that the Page is marked as Async="true" in the page directive.

Then set the Page_Load as async and when ever call the async task use await operator.

Refer below link for more details.

Using Asynchronous Methods in ASP.NET 4.5

Check with the below code.

Code

private string connection = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True;Pooling=false;";
protected async void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        await GetSomeData("SELECT * FROM Employees");
    }
}

private async Task GetSomeData(string sql)
{
    //Use Async method to get data.
    DataSet results = await GetDataSetAsync(connection, sql, null);

    //Populate once data received.
    GridView1.DataSource = results.Tables[0];
    GridView1.DataBind();
}

public Task<DataSet> GetDataSetAsync(string sConnectionString, string sSQL, params SqlParameter[] parameters)
{
    return Task.Run(() =>
    {
        using (SqlConnection newConnection = new SqlConnection(sConnectionString))
        using (SqlDataAdapter mySQLAdapter = new SqlDataAdapter(sSQL, newConnection))
        {
            mySQLAdapter.SelectCommand.CommandType = CommandType.Text;
            if (parameters != null)
            {
                mySQLAdapter.SelectCommand.Parameters.AddRange(parameters);
            }

            DataSet myDataSet = new DataSet();
            mySQLAdapter.Fill(myDataSet);
            return myDataSet;
        }
    });
}

HTML 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Async="true" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="EmployeeID" HeaderText="Id" />
                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                    <asp:BoundField DataField="City" HeaderText="City" />
                    <asp:BoundField DataField="Country" HeaderText="Country" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Output

IdFirst NameLast NameCityCountry
1 Nancy Davolio Seattle USA
2 Andrew Fuller Tacoma USA
3 Janet Leverling Kirkland USA
4 Margaret Peacock Redmond USA
5 Steven Buchanan London UK
6 Michael Suyama London UK
7 Robert King London UK
8 Laura Callahan Seattle USA
9 Anne Dodsworth London UK