In this article I will explain with an example, how to disable Enter key in TextBox to avoid PostBack in ASP.Net using C# and VB.Net.
This article will illustrate:
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?
 
 

Explanation

When one presses Enter key in the TextBox, the form gets submitted in other words PostBack occurs.
In order to disable Enter key in the TextBox, we need to first detect whether Enter key is pressed.
This can be done by detecting the keyCode of Enter key inside the onkeydown JavaScript event handler and if the keyCode is 13, we will cancel the onkeydown JavaScript event.
 
 

Disabling Enter key in TextBox to avoid PostBack in ASP.Net

There are two ways in which we can disable the Enter Key in TextBox.
1. Disable using TextBox in ASPX page
The following ASP.Net TextBox has been assigned with an onkeydown event handler. Inside the onkeydown event handler, the following expression is evaluated and if the keyCode is 13 (Enter key) then the event is cancelled.
(event.keyCode != 13)
 
<asp:TextBox ID="TextBox1" runat="server" onkeydown="return (event.keyCode!=13)"></asp:TextBox>
 
2. Disable using TextBox in Code
Inside the Page_Load event handler, the ASP.Net TextBox has been assigned with an onkeydown event handler using Attributes.Add method.
Inside the onkeydown event handler, the following expression is evaluated and if the keyCode is 13 (Enter key) then the event is cancelled.
(event.keyCode != 13)
 
C#
protected void Page_Load(object sender, EventArgs e)
{
    TextBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);");
}
 
VB.Net
Protected Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    TextBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")
End Sub
 
3. Disable using BODY in ASPX
In order to disable the Form submission on Enter key for all TextBox controls, you will need to add it to the BODY tag in the following way,
<body onkeydown = "return (event.keyCode!=13)">
 
 

Screenshots

Enabled Enter Key

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

Disabled Enter Key

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

Demo

 
 

Downloads