ASP Snippets

Categories






Alerts

Free Alerts

Your email will always be
private and will not be shared.




Follow us on twitter.




Zoom In | Zoom Out


Author is awarded Most Valuable Professional award by Microsoft ASP/ASP.Net

Disable Enter key in TextBox to avoid postback in ASP.Net

Author:Mudassar Khan

This is a default property that when one presses Enter key in the textbox the form gets submitted in other words there is a postback. So many people asked on forums

1. How to disable enter key in textbox?

2. How to prevent postback or form submission when enter key is pressed in textbox in ASP.Net?

 

So here is the neat and simple trick that does it. And the textbox below is the one that does not do a postback when enter key is pressed inside it

<asp:TextBox ID="TextBox1" runat="server"

   onkeydown = "return (event.keyCode!=13);" >

</asp:TextBox>

 

As you will notice above I wrote a simple condition on onkeydown event.

(event.keyCode!=13);

When enter key is pressed the above condition is false hence false is returned this the postback is disabled.

Note that Visual Studio will give a warning when you add onkeydown event and underline it with green.

It is just a warning and one can ignore that since Visual Studio searched for Server Side events and onkeydown is not in the list. Hence still it will work

But for those who do not want that warning can add this event from code behind

 

C#

TextBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);");

 

VB.Net

TextBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")

 

The above line will add the onkeydown event to the textbox. Make sure you add these lines to page load.


In order to disable the enter key form submission on all controls simply add it to the body tag in the following way

<body onkeydown = "return (event.keyCode!=13)">


In this way there is no need to add this event to all controls in the page.


The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari 

* All browser logos displayed above are property of their respective owners.


Posted: May 21 2009, 03:19 by Mudassar Khan | Comments (15) RSS comment feed |
Filed under: ASP.Net | JavaScript | Tips

Views: 6728
Page copy protected against web site content infringement by Copyscape


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share





Comments

Add comment


 

biuquote
  • Comment
  • Preview
Loading




0  +  0  =   










Community News





Web Hosting SpotLight


Consulting


For consulting and work related queries click here.



Advertise


Advertise with us. For more details click here.


Suggestions


Please provide your valuable suggesstions here.

This Site is hosted on

Lunarpages.com Web Hosting