Sunday, October 25, 2009

Set the DefaultFocus and DefaultButton in a master page

From ASP.NET 2.0 it is possible to set the default focus and default button with the DefaultFocus and DefaultButton properties which HtmlForm has.  DefaultFocus sets which control to get the default focus in a form, and DefaultButton decides which button will fire the click event when users hit the enter key.  In a page which uses a master page, you know the control name will be added a prefix string like ctl00_ContentPlaceHolder1_.

My example form has one EditBox named txtName and one Button named btnView.  If I use the following code in the Page_Load event:

Page.Form.DefaultButton = btnView.ID;
or
Page.Form.DefaultButton = "btnView";

I get the following error:
The DefaultButton of 'form1' must be the ID of a control of type IButtonControl.

The reason is the control name is changed in a master page.  So we have to use the following one in this case:
Page.Form.DefaultButton = btnView.UniqueID;

But for DefaultFocus, UniqueID seems not working for me.  I have to use ClientID instead of UniqueID:
Page.Form.DefaultFocus = txtName.ClientID;

An alternative is use Focus() method.  You could use the following to get the same effect as the above one:
txtName.Focus();

Sometimes you may want 2 or more default buttons on one page.  This can be implemented by putting asp:Panel control around the controls.  In the following example, when the cursor is in TextBox1, Button1 is the default button, otherwise when the cursor is in TextBox2, Button2 is the default button. 

<asp:Panel ID="Panel1" DefaultButton="Button1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</asp:Panel>
<br />
<asp:Panel ID="Panel2" DefaultButton="Button2" runat="server">
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
</asp:Panel>

No comments: