As I mentioned in my previous post, I fixed the issue of hitting enter key on an ASP.NET page with a single textbox and submit button. But now new issue occurred: I could not use the Enter key on other button web controls. Whenever I hit the Enter key in the web form, the onClick event of the search button fires not the other submit buttons. I know I am using Master page and the search button is included in every page based on this master page. And the search button is in the first button web control position.
OK, the first thing came to my mind to resolve the issue above was to use the new DefaultButton properties in ASP.NET 2.0 form or panel controls. But since I am using Masterpage, when I put defaultButton=”btnSubmit” in master page or put the following code in my Page_load event
Page.Form.DefaultButton = “btnSubmit”
I got the following error:
Server Error in ‘/MyApplication’ Application.
The DefaultButton of ‘form1′ must be the ID of a control of type IButtonControl.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The DefaultButton of ‘form1′ must be the ID of a control of type IButtonControl.
If you look close and think again, you will understand the problem here. Since the page is based on a Master Page, the HTML name and id attributes have been prefixed with the names of their naming container. Like, if you use ContentPlaceHolder1 in your master page, then your button will be “ctl00_ContentPlaceHolder1_TextBox1″.
How to resolve this problem? The trick here is to use the controls UniqueID property that returns its long client name. So, you can use the following code in your page based on Master page:
Page.Form.DefaultButton = btnSubmit.UniqueID
This way, when you press Enter, the form will post back to the server and the code in the event handler for btnSubmit.Click will fire.
The same method can be applied to defaultFocus property, of course you need to use ClientID for the textbox you need to auto-focus on.
1) The code sample above should be put in the page which is based on Master page, not the master page itself.
2), The sample code above is in VB.net, for C# you can use the following
this.form.DefaultButton = this.yourbutton.UniqueID