ASYNCHRONOUSLY POPULATE GRIDVIEW ON BUTTON CLICK

jayprakash sharma

Total Post:117

Points:821
Posted by  jayprakash sharma
 1829  View(s)
Ratings:
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. 


  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Asynchronously populate gridview on button click

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!