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">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

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.

No comments:

Post a Comment