View Single Post
  #2 (permalink)  
Old May 29th, 2011, 02:43 PM
mhanson mhanson is offline
Authorized User
Points: 73, Level: 1
Points: 73, Level: 1 Points: 73, Level: 1 Points: 73, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: Jul 2007
Location: , , .
Posts: 17
Thanks: 0
Thanked 0 Times in 0 Posts
Default Callback Asynchronous Command Execution using ADO.Net


I was having the same problem. I found the answer in another Wrox forum by Pegasus40218:

BOOK: Professional ASP.NET 3.5 SP1 Edition: In C# and VB,

It is in VB but easy to convert to C#. This is an event issue. The Page_Load event completes before the data is bound to the grid. This is why we sometimes see the data. Add a loop to delay the Page_Load event. I did so my adding a bool AsyncDone at the class level. Adding a While(AsyncDone == false) loop at the end of the Page_Load event. And finally adding the AsyncDone field at the end of the CBMethod callback. The added lines of code are bold. Below is the listing. I hope this helps

public partial class Listing_08_35a : System.Web.UI.Page
bool AsyncDone = false;
protected void Page_Load(object sender, EventArgs e)
SqlConnection DBCon;
SqlCommand Command = new SqlCommand();
IAsyncResult ASyncResult;
DBCon = new SqlConnection();
Command = new SqlCommand();
DBCon.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
// Selecting top 5 records from the Orders table
Command.CommandText =
"SELECT TOP 5 Customers.CompanyName, Customers.ContactName, " +
"Orders.OrderID, Orders.OrderDate, " +
"Orders.RequiredDate, Orders.ShippedDate " +
"FROM Orders, Customers " +
"WHERE Orders.CustomerID = Customers.CustomerID " +
"ORDER BY Customers.CompanyName, Customers.ContactName";
Command.CommandType = CommandType.Text;
Command.Connection = DBCon;
// Starting the asynchronous processing
ASyncResult = Command.BeginExecuteReader(new AsyncCallback(CBMethod), Command, CommandBehavior.CloseConnection);
while(AsyncDone == false)
public void CBMethod(IAsyncResult ar)
SqlCommand command = (SqlCommand)ar.AsyncState;
// Retrieving result from the asynchronous process
SqlDataReader OrdersReader = command.EndExecuteReader(ar);
// Displaying result on the screen
gvOrders.DataSource = OrdersReader;
AsyncDone = true;
This is frustrating to me. I can't believe we are the only ones experiencing this problem. Also, this problem existed in ASP.NET 3.5 SP1. Why wasn't this corrected in subsequent editions.

Not sure what the CODE and QUOTE tags do. I thought they would format the code. Sorry.