tags:

views:

173

answers:

4

How can we handel key pressed event in asp.net

A: 

It depends on your situation. In most cases, you will have to handle keypressed event in javascript, and somehow propagate that event to server side. Consider revising your question to include more background.

Salamander2007
+1  A: 

Presumably you mean from the website itself. ASP.NET has no support for this, you will need to capture the keypress with javascript and then send it to ASP.NET via ajax or lightweight callbacks.

Andrew Bullock
+1  A: 

You have to handle this client side, in Javascript, then either post back the page, or call an Ajax method to do something.

For instance the following code overrides a text box so that Enter doesn't submit it:

<asp:TextBox 
    runat="server" 
    onKeyPress="if (event.keyCode == 13) return false;" />

This is a very simple call - if you're planning do do anything more complex check out dedicated Javascript libraries like JQuery.

Keith
+1  A: 

You can handle it on client side with javascript:

myTextBox.Attributes["OnKeyPress"] = "javascript function call;";

You can use OnKeyUp for a better browser compatibility and handling.

You can also handle something similair on server side:

<asp:TextBox runat="server" ID="ole" ontextchanged="ole_TextChanged" AutoPostBack="true"></asp:TextBox>

protected void ole_TextChanged(object sender, EventArgs e)
{
    // Do stuff
}

However this fires only when you leave the field, and anyway I wouldn't recommend it as it is using a postback every time.

The solution is anyway to go with javascript. It can be simple javascript, or AJAX.

Biri