User Controls and Client Side Scripting - Starting Our User Control
(Page 2 of 3 )
In your favorite editor write the code for UserControl. Add the control directive to indicate it is the UserControl.
<%@ Control Language="Vb" %>
<Asp:checkBox Id="MyCheckBox" runat="Server" onClick="javascript:check('MyTagCtl_MyText','Teal');"/>
<Asp:TextBox Id="MyText" runat="Server" />
Observe that I am not adding any java script to the TextBox at Declaration but for CheckBox. You can add other stuff for your control here, then add the server side scripting if necessary. I am using this area to add functionality to the TextBox.
<Script Langugae="Vb" runat="Server">
Public Sub Page_Load()
MyText.Text="Click Here"
MyText.Attributes.Add("onClick","changeColor('MyTagCtl_MyText','Silver')")
End Sub
</Script>
Notice that we can add script with Attribtes.Add method. This method has two parameters. The first one is the attribute name and the later is the value for the attribute. We are using this method to add java script function to our TextBox.
The Load event is same as Page_load of the web form. In case our control needs some client side scripting we can add with Script Tag. I am adding the javascript functions which will change the TextBox BackGround Color.
<script language="JavaScript" type="text/JavaScript">
function changeColor(ctlId, newColor)
{
document.getElementById(ctlId).style.backgroundColor = newColor;
}
function check(ctlID,newColor)
{
document.getElementById(ctlID).style.backgroundColor = newColor;
}
</script>
We can add the javascript for the controls in the Aspx form where it is called, but it will be more meaningful to add it to the control itself so that calling form need not bother about the implementation. While referring the control we are not only using the control ID, but the TagID, which we will use in the Aspx form. It might be confusing at first, but the simple explanation is when controls are rendered on the form, it acquires the TagId used in the form and concatenates with the Id used in the user control to avoid any ambiguity with the controls used on the form. We will see details in implementation soon. Finally save the file with “Ascx” extension (MyScriptControl.Ascx).
Next: Utilizing the UserControls >>
More ASP.NET Code Articles
More By JB Reddy