Karatas, FERHAT
I would love to change the world, but they won't give me the source code!
DefaultButton in a Page Based on a Master Page
3.7.2007 11:29:38 - Filed under : Asp.net
You may be aware of the new DefaultButton and DefaultFocus properties that a few ASP.NET 2.0 controls, including the HtmlForm have. These properties allow you to determine which button gets "clicked" when you hit enter on the page, and which form control gets the focus when the page loads.

Your first attempt may be to add the following code in the Page_Load event of the Content page:

  Page.Form.DefaultFocus = "TextBox1"
  Page.Form.DefaultButton = "Button1"

However, as soon as you run this code, you'll get the following error:

Server Error in '/MyApplication' Application.
The DefaultButton of 'form1' must be the ID of a control of type IButtonControl.
Exception Details: System.InvalidOperationException: The DefaultButton of 'form1' must be the ID of a control of type IButtonControl.

Because the page is based on a Master Page, the HTML name and id attributes have been prefixed with the names of their naming container, the ContentPlaceHolder1 in this case.

Now how do you get the correct client id inside the call to WebForm_AutoFocus? The trick here is to use the controls ClientID property that returns its long client name. If you change the code in the code behind to the following, the DefaultFocus will work:
Page.Form.DefaultFocus = TextBox1.ClientID
You can apply the same technique to set the DefaultButton but then you should use its UniqueID property:
Page.Form.DefaultButton = Button1.UniqueID
This way, you end up with a form that has the focus on the TextBox1 by default and when you press Enter, the form will post back to the server and the code in the event handler for Button1.Click will fire.

Keywords : DefaultButton, DefaultFocus, Master Page, asp.net 2.0
with 0 comments

What do you think ?
Security Code 7617
Check S. Code
Name  
Email  
Home Page  
Comments