Tuesday, March 31, 2009

Monitor pressed keys in C# ASP .NET text box controls

Similar to the way you can add a confirmation dialog box to a form, you can also monitor keystrokes within your text boxes and fire events off depending on which button is being pressed. This can help restrict certain buttons, or provide a specific key combination to perform a certain actions. Here's how to do it:

protected void Page_Load(object sender, EventArgs e)
{

if(!IsPostBack)
{
TextBox1.Attributes.Add("onkeydown", "if((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {alert('Please do not use the Enter key'); return false;} else return true;");
}

}

What this code does is define the "onkeydown" attribute for the text box named "TextBox1". In the example, it checks to see if the user is pressing the Enter key, and if so, displays an alert dialog box telling them not to. By having it return false, it then does not process that keystroke either. If they do not press Enter, then it returns true and the character they typed shows up in the text box. 

My need for this is that I didn't want users pressing Enter to skip lines in a multi-line text box. This worked perfectly, and could be used for all kinds of other purposes related to which keys are pressed at a certain point within a form. The original post I used to come up with this can be found here.

No comments: