Decrease Font Size
Increase Font Size
   BLOG

ASP.NET - How to set DefaultButton in a page that are using master page

Watch this Script in action

ASP.NET DefaultButton with MasterPages.

How To set Default Button for ENTER key pressed event

How to set DefaultButton in a page that are using master page.

Sometimes we might have two or more ASP.NET button control on the ASP.NET page and prefer certain button to cause postback when the ENTER key is pressed. The DefaultButton attributes on the HtmlForm control allow us to set the button control that will causes postback when the ENTER key is pressed. Here is a small demonstration on how to set the default button in a page with using master page.

.aspx page

<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" Runat="Server">
 
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <br />  <br />
    <asp:Button ID="Button1" runat="server" OnClientClick="javascript:alert('btn 1');" Text="Button 1" OnClick="Button1_Click" />
    <br />
    <asp:Button ID="Button2" runat="server" OnClientClick="javascript:alert('btn 2');" Text="Button 2" OnClick="Button2_Click" />
   <br />
    <asp:Button ID="Button3" runat="server" OnClientClick="javascript:alert('btn 3');" Text="Button 3" OnClick="Button3_Click" />
    <br />
   <asp:Button ID="Button4" runat="server" OnClientClick="javascript:alert('btn 4');" Text="Button 4" OnClick="Button4_Click" />
  <br />  <br />  <br />  <br />
</asp:Content>

.cs page

protected void Page_Load(object sender, EventArgs e)
    {
        Page.Form.DefaultButton = Button4.UniqueID;
        Page.SetFocus(TextBox1);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "You typed in: " + TextBox1.Text + " You clicked on button1 on " + DateTime.Now.ToLongTimeString();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Label1.Text = "You typed in: " + TextBox1.Text + " You clicked on button2 on " + DateTime.Now.ToLongTimeString();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        Label1.Text = "You typed in: " + TextBox1.Text + " You clicked on button3 on " + DateTime.Now.ToLongTimeString();
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        Label1.Text = "You typed in: " + TextBox1.Text + " You clicked on button4 on " + DateTime.Now.ToLongTimeString();
    }