C# – GridView.PageSize set to default 10 on 1st page load

asp.netcgridviewpageload

I am using C#, .NET 3.5. I have a GridView control with dynamically bound DataSource and I set the PageSize dynamically in the Page_Load event handler. I have set AllowPaging = true on the control.
The GridView paging is working fine, however the pagesize set in Page_Load does not take effect the first time that the page is loaded. The first time that the page is loaded, it will always display 10 rows irrespective of the GridView.PageSize property that I have set (5, 15 etc). After the 1st time (page postback), the page size takes effect and everything works as expected.

The Page size is a property of the Master Page that I get from the web.Config file under appsettings.

I am not sure why the pagesize of the gridView does not take effect the 1st time. Should I be setting the pagesize in another event other than the Page_Load. Also, I am setting it always, even if its a postback. I am running the page using the internal web server. Any idea whats happening?

code behind (GridView1.AllowPaging = true on aspx page):

  protected void Page_Load(object sender, System.EventArgs e)
  {
                        DataView dvMembers = GetMembers;

                        GridView1.DataSource = dvMembers;   
                        GridView1.PageSize = Master.GridViewSize;
  }

Master page property :

public int GridViewSize
    {
        get { return Convert.ToInt32 
                (ConfigurationManager.AppSettings ["memberDataGridPageSize"]); } 
    }

Best Answer

The PageLoad event of your child page is called before the PageLoad event of your master page. Therefore, if you are setting Master.GridViewSize in the master page PageLoad event, it is not set until the second PostBack.

It would be better to load the GridViewSize early in the page lifecycle and then store it in the session.

Related Topic