Link to home
Start Free TrialLog in
Avatar of zintech
zintech

asked on

How to register KeyPressed event in C# ASP.NET

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.
Avatar of HainKurt
HainKurt
Flag of Canada image

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>
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

Avatar of zintech
zintech

ASKER

So you are saying I need to register the control on the ASP.NET side then in the HTML, okay
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

Avatar of Mlanda T
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....
the samples I posted are all on client side, I dont even think of server side firing for each key event...
ASKER CERTIFIED SOLUTION
Avatar of Mlanda T
Mlanda T
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial