asp.net.ph

Skip Navigation Links

Responding to Changes in a TextBox Control

Controls You Can Use on Web Forms   ASP.NET Standard Controls   TextBox Control


When a user leaves a TextBox control after entering information, the control raises an event that you can respond to.

NOTE: The TextBox control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes. For details, see Programming Web Forms with Client Script.

To respond to changes in the TextBox control

  1. Define a method to handle the control’s TextChanged event.

private void myTextHandler ( object src, EventArgs e ) {
   // ... do something amusing here ...
}
  C# VB
  1. Assign the handler to the onTextChanged event attribute of the TextBox control.
<asp:TextBox onTextChanged="myTextHandler" runat="server" />

By default, the TextChanged event does not immediately cause the Web Forms page to be posted to the server. Instead, the event is raised in server code the next time the form is posted, as when a Button Web server control is clicked. To have the TextChanged event cause an immediate posting, set the TextBox control’s AutoPostBack property to true.

NOTE: The ability of a TextBox control to post automatically to the server when it’s text is changed requires that the browser support ECMAScript and that scripting is enabled on the user’s browser.

The following example shows how you can respond to changes in a TextBox control when its TextChanged event occurs. In this case, the code simply displays the contents of the control in a label.

Responding to Changes in a TextBox Web Control
Run Sample | View Source

NOTE: User input in a Web Forms page can include potentially malicious client script. By default, the Web Forms page validates that user input does not include script or HTML elements. In addition, authors can apply HTML encoding to strings to protect against script exploits in a Web application.

private void myTextHandler ( object src, EventArgs e ) {
   ...
   msg.Text = Server.HtmlEncode ( myTextBox.Text );
}
  C# VB

See Also

Web Forms Events and Handlers   Setting Web Server Control Properties Programmatically



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note