more debugs

Sunday, November 27, 2011

Creating Fixed Headers in an ASP.Net GridView using JavaScript

In Reference to  article in CodeProject particular article Grid View With Fixed Header I am stating the problem first and stating the solution.

Problem : Whenever we use grid view along with a webform which include master page. I mean if we place gridview in the ContentPlaceHolder, then the ID of the Grid View is found to be changed
So when we try to pass the ID (GridView1 in above mentioned example) we ge some error due to not finding the id by javascript on runtime.





Solution :
Replace
  ClientScript.RegisterStartupScript(this.GetType(), "CreateGridHeader", "<script>CreateGridHeader('DataDiv', 'GridView1', 'HeaderDiv')</script>");
     
 with
     System.Web.UI.Control cd = Page.Master.FindControl("GridView1");
      if (cd != null)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "CreateGridHeader", "<script>CreateGridHeader('DataDiv', 'GridView1', 'HeaderDiv')</script>");
        } 
  // name of the gridview changes on fly when using with master page
        ClientScript.RegisterStartupScript(this.GetType(), "CreateGridHeader", "<script>function PageLoad(){CreateGridHeader('DataDiv', 'ctl00_ContentPlaceHolder1_GridView1', 'HeaderDiv');}</script>");



and add following code to body tag of master page (.aspx)

<body onLoad="PageLoad()">


And get the grid view working as described in code project.



Thank you.

Follow Me 



  

5 comments:

  1. I have been looking for this exact solution for hours! However, I don't understand the replacement script - do I need all of it? It seems to call the methiod twice...

    ReplyDelete
  2. if you can see if(cd != null) then you will be able to understand the its not calling the method twice but calling the method as // name of the gridview changes on fly when using with master page,
    so calling onload of the body.

    ReplyDelete
    Replies
    1. OK - followed the example. Getting Object Expected at body onload="PageLoad()" in site.master


      Is something missing? I'm sorry - I don't quiote understand what is supposed to be happening when cd is null. Using VS2010 - updated body tag in site.master and put the rest of the code in Default.aspx. Still not getting a handle to the grid control.

      What is 'ctl00_ContentPlaceHolder1_GridView1'?

      Delete
  3. when cd is null we register StartupScript........

    ReplyDelete
  4. And ctl00_ContentPlaceHolder1_GridView1 is what a gridview id GridView1 is replaced upon placing inside masterpage......

    ReplyDelete