Main FAQ Category: WebForms (12)
Why Button Click event handler code is not executed when Enter key is pressed on ASP.NET Form?
Posted: 7-Apr-2008
Updated: 7-Apr-2008
Views: 10110

Subtle differences in how Internet Browsers function and internally handle your ASP.NET pages can sometimes cause many sleepless nights.

Here is great example of one of those weird bugs:

If you happen to have a ASP.NET page with WebForm that has SINGLE Textbox Control with any other components, and submit Button control with some code in Click event handler, and if user opens this page in Internet Explorer and tries to submit the form by pressing Enter Key, the form will get posted, but the code in Button Click event handler will NOT get executed!!!

If user opens the same page in some other modern browser (Firefox, Opera etc) all will run like expected: pressing the Enter key will submit the form and Click event handler code of submit Button will get executed.

Weird enough for you?

To make thing even more strange, if there are more than one Textbox controls on the page, everything will run fine even in Internet Explorer!
So to summarize the problem: Only ASP.NET pages with single Textbox component viewed in Internet Explorer are affected by this bug.

To avoid this behavior we can do two things:

First we can add another TextBox control to our form and make it invisible by CSS style and everything would work fine:

<asp:TextBox ID="InvisibleTextBox" runat="server" Style="visibility:hidden;display:none;" /> 


This works, but it is a hack.

There is cleaner solution: we can use the DefaultButton property of the ASP.NET Form control like this:

<form id="form1" runat="server" defaultbutton="MySubmitButton" >

 

By setting the DefaultButton property in our web form, ASP.NET will generate this HTML code in our page:

<form name="form1" method="post" action="SomePage.aspx" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'MyButton')" id="form1"

Eventually, when user clicks Enter key on the form, JavaScript function called FireDefaultButton will be called and that will submit our WebForm properly in even in the Internet Explorer.

Thats it, another day, another workaround found.