Home > DeveloperSection > Forums > Asynchronously populate gridview on button click
jayprakash sharma
jayprakash sharma

Total Post:117

Points:821
Posted on    May-13-2013 3:27 AM

 ASP.Net ASP.Net 
Ratings:


 1 Reply(s)
 1461  View(s)
Rate this:
Hi Expert! 

I would like to populate a Gridview which is inside an update panel on button click. Currently the gridview is getting populated however doesn't show up on screen. How to achive it? My line of code as following. 

  public delegate void BindGrid_Delegate();
  protected void btnSearch_Click(object sender, EventArgs e)
  {
        try
        {
            // databind of all the controls
            BindGrid_Delegate bd = new  BindGrid_Delegate(BindGrid);
            IAsyncResult ar = bd.BeginInvoke(null, null); //invoking the method
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "PageException", "alert('" + ex.Message + "');", true);
        }
  }

  private void BindGrid()
  {
      try
      {
          DataSet ResultDataSet = GetData();
          gvShowResult.DataSource = ResultDataSet; 
          gvShowResult.DataBind();
          UpdatePanel2.Update();
      }
      catch (Exception ex)
      {
          ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "PageException", "alert('" + ex.Message + "');", true);
      }
  }

Updatemode for updatepanel is conditional.

Thanks in advance!
Any help will be appreciated. 




AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-13-2013 9:35 AM

Hi Jayprakash!

The problem could be that you call DataBind() and Update() on the non-UI thread. UI controls should only be modified on the thread that creates them.

You can still call your GetData() method in a separate thread, e.g. using Tasks.

In your btnSearch_Click method:

Task.Factory
    .StartNew(() => GetData())
    .ContinueWith(t => 
    {
        gvShowResult.DataSource = t.Result; 
        gvShowResult.DataBind();
        UpdatePanel2.Update();
    }, TaskScheduler.FromCurrentSynchronizationContext());

This calls GetData() on a separate thread and executes the continuation on the UI thread.

Don't want to miss updates? Please click the below button!

Follow MindStick