2015年9月1日 星期二

[ASP.NET] 讓 Textbox 按 ENTER 時 postback 失效

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