We help IT Professionals succeed at work.

How to register KeyPressed event in C# ASP.NET

zintech
zintech used Ask the Experts™
on
I have a methord called

 TextBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)

That I would like to register and have fire on the Textbox named TextBox1 when the user presses a ley up but I do not know how to register it or use it.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
HainKurtSr. System Analyst

Commented:
is this web application? do you want to run a javascript function on client, not server, correct?

if yes,

TextBox1.attributes("onKeyPress","js_KeyPressed(event, this)")

and add a js function

<script>
function js_KeyPressed(event, sender){
  alert(event.key); alert(sender.id);...
}
</script>
HainKurtSr. System Analyst

Commented:
oops, it should be keyCode... your rendered page should look like this
<script>
function js_KeyPressed(event, sender){
  alert(event.keyCode); alert(sender.id);
}
</script>
<input id=txtTest onKeyPress="js_KeyPressed(event, this)">

Open in new window

Author

Commented:
So you are saying I need to register the control on the ASP.NET side then in the HTML, okay
HainKurtSr. System Analyst

Commented:
when you use this

<asp:Textbox id=test runat=server>
...
TextBox1.attributes("onKeyPress","js_KeyPressed(event, this)")

it is rendered as

<input id=xxx_xxx_xxxx_test onKeyPress="js_KeyPressed(event, this)">

and on the page if you have that js function it will be called whenever you press a key inside that box

It's not good practice to fire up server side code like that in a web application - at least not for each keypress. It's fine for desktop applications. What are you trying to achieve?

It is best practice to process the key press in client side script, and I prefer using jQuery (http://dotnetstars.blogspot.com/2011/02/adding-keypress-event-to-all-textboxes.html) for this sort of thing because it is cleaner and peformance-wise, will remain fast. The best guidance will really depend on what you are doing in the " TextBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)" method. First try to do it all in javascript, and if thats not possible, consider asyncronous javascript calls to the server....
HainKurtSr. System Analyst

Commented:
the samples I posted are all on client side, I dont even think of server side firing for each key event...
@HainKurt... my comments were in fact directed to the author
TextBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)

Open in new window

looks like server side code to me, and worse... something typical of a windows forms application.