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
Id | First Name | Last Name | City | Country |
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 |