Javascript functions inside ASP.NET User Control

I created ASP.NET user control with javascript function :

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="BingTranslator.Web.WebUserControl1" %>
<script type="text/javascript">
    function example() {
        alert('<%=ExampleButton.ClientID%>');
        return false;
    }
</script>
<asp:Button ID="ExampleButton" runat="server" Text="Example"/>

I want to call “example” function when user move mouse to button, so I added attribute for button:

ExampleButton.Attributes.Add("onmouseover", "example()");

It works well, but when I need two controls on same page I got a problems. ASP.NET generates code with two functions with same name, what is wrong:

<script type="text/javascript">
    function example() {
        alert('TestControl1_ExampleButton');
        return false;
    }
</script>
<input type="submit" name="TestControl1$ExampleButton" value="Example" id="TestControl1_ExampleButton" onmouseover="example()" />


<script type="text/javascript">
    function example() {
        alert('TestControl2_ExampleButton');
        return false;
    }
</script>
<input type="submit" name="TestControl2$ExampleButton" value="Example" id="TestControl2_ExampleButton" onmouseover="example()" />

And always onmouseover event on any button will call second function. I am able resolve this issue by adding java script code with client Id directly to attriburte onmouseover.

ExampleButton.Attributes.Add("onmouseover", "[Here will be javascript code]");

But it is not very harmonious solution as for me. Please advise, how I can better resolve such issue.

P.S. There will be much more Javascript code, I added two string upper just for example.

Answer

You need to register your scripts with ClientScriptManager – this way they can be registered once, regardless of how often the control has been added to the page:

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
  String cstext1 = "alert('Hello World');";
  cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}