Tuesday, April 15, 2008

Execute a JavaScript in PageLoad , when using custom controls in ASP.NET

I know that most of you are familiar with adding client side scripts in ASP.NET custom controls for various events, preferably for ‘onclick’ event of controls. The common way is adding script as an attribute of the control.

btnSubmit.Attributes.Add("onClick", "enableDateValidator();
document.getElementById('lblE').style.display='none';")


Here is the way to add a JavaScript, which will be run on pageload.

Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)

Dim script1 As String
script1 = " alert(‘Test’);"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "EnableDisableControlScript1", script1)

End Sub

It is important to note that, if you are using ClientID of any control, implement the script inside the OnPreRender Overrides method. Otherwise you may face some problems with client side ID of your control.

No comments: