Pages

Wednesday, November 9, 2011

Disable post back on enter key in TextBox


By default when you hit enter while cursor is in the TextBox, the first button on the page event gets fired.
I have added a TextBox and a Button in the aspx page like below
<asp:TextBox ID="TextBox1" runat="server"><asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
And the below code in the code behind
protected void Button1_Click(object sender, EventArgs e)
{
   Response.Write("Button1"
);
}

Now run the application and hit enter key while cursor is in TextBox, you will notice that "Button1" printed on the page.
To avoid executiong of code behind of the button put
OnKeyDown = "return (event.keyCode!=13);"
in the TextBox like below
<asp:TextBox ID="TextBox1" OnKeyDown = "return (event.keyCode!=13);" runat="server">asp:TextBox>
Now run the application again and hit enter key, this time Button Click even will not fire.
Live Demo

No comments:

Post a Comment