Showing posts with label client event handler. Show all posts
Showing posts with label client event handler. Show all posts

Saturday, December 17, 2011

How to add a client event handler to an ASP.NET control programmatically

You can add client script to controls on an ASP.NET Web page declaratively, as you would to HTML elements (see recent post). Alternatively, you can also add client script events to an ASP.NET Web server control programmatically, which is useful if the event or the code relies on information that is available only at run time. In the page's Init or Load event, call the Add method of the control's Attributes collection. The following code example shows how to add client script to a TextBox control. The client script displays the length of the text in the TextBox control in other TextBox.

Here is form tag.
<form id="form1" runat="server">
     <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    </div>
</form>

In your code-behind,
protected void Page_Load(object sender, EventArgs e)
{
    String displayControlName = TextBox2.ClientID;
    TextBox1.Attributes.Add("onkeyup", displayControlName +
        ".value=" + TextBox1.ClientID + ".value.length;");
}


 That's it. Thank.

How to add a client event handler to an ASP.NET server control declaratively

You can add client script to controls on an ASP.NET Web page declaratively, as you would to HTML elements. In the control's markup, add an attribute for the event, for example, onmouseover or onkeyup. For the attribute's value, add the client script that you want to execute. The following code example shows an ASP.NET Web page that includes client script that changes the button text color when the user passes the pointer over it.
 
Here is javascript.
 <script type="text/javascript">
        var previousColor;
        function MakeRed(e) {
            var targ;
            // e gives access to the event in all browsers
            if (!e) var e = window.event;
            if (e.target) targ = e.target;  //for IE
            else if (e.srcElement) targ = e.srcElement;  //for Firefox
            previousColor = targ.style.color;
            targ.style.color = "#FF0000";

        }
        function RestoreColor(e) {
            var targ;
            if (!e) var e = window.event;
            if (e.target) targ = e.target;
            else if (e.srcElement) targ = e.srcElement;
            targ.style.color = previousColor;
        }
    </script>

 Here is form tag.
<form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button1" onmouseover="MakeRed(event);"
            onmouseout="RestoreColor(event);" />
    </div>
 </form>

See the other example : http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx