Textbox field do postback on pressing "Enter"


This is probably more an annoyance that a problem, but is there any way to disable an ASP.NET textbox control from doing a postback when punching the Enter key while the textbox is in focus.
For instance, on a login page, i type the username & password in the respective fields, but unless i actually click the submit button, the page just reloads.

I remember that in ASP 3.0 punchine the Enter key would automatically activate the first button control in the form.

many thanks!
Who is Participating?
Jason ScolaroCommented:
Hi split-etm-,

This is made incredibly easy with ASP.NET 2.0.  This article discusses both ASP.NET 1.1 and 2.0 (see bottom of page for 2.0 solution):

-- Jason
Just add this to the attributes of whichever text box you want to do a postback from:

TextBox.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + Button.UniqueID + "','')");
Why not just do this:

TextBox.Attributes("onKeyUp") = "javascript:if (event.keyCode==13){btnLogin.click();}")

And it will submit the form by simulating the login button being clicked. If it has trouble locating the button just use this:

TextBox.Attributes("onKeyUp") = "javascript:if (event.keyCode==13){document.getElementById('btnLogin').click();}")

and that will single out just that one button in case you should have other controls by the name of "btnLogin."
split-etm-Author Commented:
noamattd: thanks for your post. your method worked fine, but caused a javascript error to appear in IE though because for some reason the __doPostBack javascript event wasnt available once the page was built & run.

wtconway: thanks for your post. your method also worked, but caused my validation box to popup twice for some reason.

i finally got it working 100% using code i found on the link scolja posted. thanks for that scolja.

thanks to all for the replies. :)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.