3

I want to call a javascript function when the gridview loads. Im calling it like this,

<asp:GridView ID="GridView4" runat="server" OnLoad="javascript:AddTHEAD('<%= GridView4.ClientID %>')">
</asp:GridView>

and here is the javascript function

<script type="text/javascript">
        function AddTHEAD(tableName) {
        window.open(document.location.href+'&mode=print','_blank');
            var table = document.getElementById(tableName);
            if (table != null) {
                var head = document.createElement("THEAD");
                head.style.display = "table-header-group";
                head.appendChild(table.rows[0]);
                table.insertBefore(head, table.childNodes[0]);
            }       
        }         
</script>

But im getting compilation errors on calling javasccript function like this. How to call javascript function on the OnLoad event of GridView? What i want to do is basically print gridview header on each page, but i couldn't figure out how. Please help!

1
  • try calling AddTHEAD() method in document ready function using jquery Commented Jul 22, 2014 at 17:17

1 Answer 1

1

I don't see an OnLoad event in gridview, but I do see a Load event. Inside this event I would use scriptmanager to call a javascript function from the code behind. Here is an example:

Protected Sub gridCreditLines_ExistingGlobal_Load(sender As Object, e As EventArgs) Handles gridCreditLines_ExistingGlobal.Load

    ScriptManager.RegisterStartupScript(Page,
                                        Page.GetType(),
                                        "AddTHEAD",
                                        "AddTHEAD(" & tableName & ");",
                                        True)

End Sub

Using scriptmanager may require you to add a scriptmanager control to your form:

    <ajaxToolKit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </ajaxToolKit:ToolkitScriptManager>

I'm sure there is a little more to it to hook this into your existing code, but this should at least point you to the right direction. This technique always works for me when trying to call my js functions from the VB code behind.

Sign up to request clarification or add additional context in comments.

2 Comments

how should i pass the client id of gridview to AddTHEAD function, like this ScriptManager.RegisterStartupScript(Me, Me.GetType(), "AddTHEAD", "AddTHEAD(GridView4.ClientID);", True)? Is the syntax in bold correct?
i believe you could just use sender.ClientID, but your way should work too ... take a look at this to explain the sender.ClientID: stackoverflow.com/questions/1303145/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.