Take advantage of DefaultButton property in ASP.NET 2.0

If you are new to ASP.NET 2.0, then this would be good news to you! If you have more than one button on a form and if you wanted to keep a specific button as default one, then the DefaultButton property helps you to specify any button on a form as the default button when the form loads.
(For a new commer to the web development, the default button is the button which will post back to the server if you press the ENTER key)

 

For example, if you wanted to specify SubmitButton as a default button, then the syntax would be as shown below.

<form id="Form1"

    defaultbutton="SubmitButton"

    defaultfocus="TextBox1"

    runat="server">

 

Complete example:

<%@ page language="C#" %>

 

<html>

<head>

  <script runat="Server">    

  

    void Page_Load(object sender, System.EventArgs e)

    {

      Label1.Text = "The DefaultButton property is set to "

                    + Form1.DefaultButton.ToString() + "<br/>";

      Label2.Text = "The DefaultFocus property is set to "

                    + Form1.DefaultFocus.ToString();

     }

 

      void CancelButton_Click(object sender, EventArgs e)

      {

          Response.Write("Cancle is clicked");

      }

</script>

</head>

<body>

  <form id="Form1"

    defaultbutton="SubmitButton"

    defaultfocus="TextBox1"

    runat="server">

   

    <h3>DefaultButton and DefaultFocus Properties Example (2.0)</h3>        

 

    TextBox1:

    <asp:textbox id="TextBox1"

      autopostback="true"

      runat="server">

    </asp:textbox>

 

    <br />

 

    TextBox2:

    <asp:textbox id="TextBox2"

      autopostback="true"

      runat="server">

    </asp:textbox>

 

    <br /><br />

 

    <asp:button id="SubmitButton"

      text="Submit"

      runat="server">

    </asp:button>

 

    <asp:button id="CancelButton"

      text="Cancel"

      runat="server" OnClick="CancelButton_Click">

    </asp:button>

 

    <hr />

 

    <asp:label id="Label1"

      runat="Server">

    </asp:label>

 

    <asp:label id="Label2"

      runat="Server">

    </asp:label>

 

  </form>

</body>

</html>

 

Hope it helps you!

45 Comments

  • Nice to have one defaultbutton.. is it mandatory to have autopostback enabled on all controls??



    Now I want to have multiple forms and each form with it's own default button as we have always used prior to ASP.NET



    It is a pain in the ass to only have one serverside form. Everyone it complaining that you shouldn't use framesets for obvious reasons. Not a problem if you can use multiple forms on one page (for example, one form for global site search, one for the main content, one for login in. This maintains quite well and even fits the ASP.NET control profile. It would map very well when you could create a form as a sort of control.



    Each form has it's own default action and (clientside!) validation. If you want this behaviour in ASP.NET you must disable all client-site validations and depending button pressed you must enable the validators in a specific control and call the page Validate method and IsValid property to see if the submitted content is ok. This is stupid! When not implemented the page just submits itself and does nothing! Thus making a useless roundtrip!



    I like ASP.NET very much but some thing like this really make my irritated because this was always really easy to use prior to ASP.NET. With helpers classes/baseclass methods and lot's of javascript it is possible to create the same experience for the end user but WHY should I have to do that with just ONE form when using multiple forms develops much easier?



    Maybe it is just me who is irritated by this design/behaviour...

  • Good news, so I will no longer have to embed two javascripts (one for default button and one for default focus) on every form...

  • Ramon:

    For obvious reasons I was not in favour of having Multiple forms on the same page!



    I guess your business requirement might demanded to use it! That would be one reason I can think why you gone for that design!

    As an alternative see if Wizard control helps you now! (It won't be as multiple forms on the page, but it's more flexible for that kind of desing and it's an alternative!)



    Alan:

    Yep! You no longger need to two javascripts. how cool it is!!! :)

  • You can have a DefaultButton set for each 'Panel' and put your sections of the form in Panels...

    Not a solution, but a better way of working with what we've got.

    (he says 3.5 years later)

  • With DefaultButton set for a panel, the javascript validation script given for the button, is not working properly. The validation script, whether it returns true or false, the server sider onclick triggers. I want it to be triggered only if javascript returns true ?!!!


  • Hi Valli,

    I have similar requirements and, adding the defaultbutton attribute to the panel, worked for me.

    Below is my code:
    1. ASPX























    2. Code-behind:
    protected void Page_Load(object sender, EventArgs e)
    {
    if(!IsPostBack)
    {
    btnsubmit1.Attributes.Add("OnClick", "return fnsubmit();");
    txtValue.Focus();
    }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
    txtValue.Text = "submitted";
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
    txtValue.Text = "cancelled";
    }

    Thanks,
    Viswanathan

  • All is well, only one big missout, if you specify the default button than even if you go by pressing TAB to cancel button and press Enter key , instead of firing cancel event it go for default button click, what the missout. what a big bug.
    do anybody have solution for this?

  • What's "Cancle is clicked"

  • Imran, if you can rephrase your question, I might be able to help.

    Ok, a bit of a headache there, but if you stick the Cancel button (which, btw, is just a normal button) with a defaultButton value of a button that submits the page, it will submit the page.

    Not a bug on Microsoft's part. You can stick your Cancel button in it's own panel to specify it's defaultButton to be your desired action.

  • Excellent web site. Plenty of useful information here.

    I am sending it to several buddies ans additionally
    sharing in delicious. And certainly, thanks to your effort!

  • I'm amazed, I must say. Rarely do I come across a blog that's both equally educative and entertaining,
    and let me tell you, you have hit the nail on the head.
    The issue is something which not enough men and women are speaking intelligently about.
    Now i'm very happy I found this during my search for something regarding this.

  • When someone writes an post he/she keeps the idea of
    a user in his/her brain that how a user can understand it.
    So that's why this post is outstdanding. Thanks!

  • Hi this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually
    code with HTML. I'm starting a blog soon but have no coding knowledge so I wanted to get advice from someone with experience. Any help would be greatly appreciated!

  • We returned to check what you tend to be creating this time around.

  • Kept up to date Guidance On Smart Software programs To Have claim

  • Picking No-Absurdity Solutions For car or truck applications available
    for sale

  • We stumbled over here from a different web page and thought I might as well check things out.
    I like what I see so now i am following you.
    Look forward to going over your web page repeatedly.

  • 5 Search engine marketing Tricks to Improve The search engines Image Investigation Targeted traffic

  • You really make it seem so easy with your presentation but I find this matter to be really something which
    I think I would never understand. It seems too
    complicated and very broad for me. I'm looking forward for your next post, I will try to get the hang of it!

  • Synopsis on Veranda Pavers

  • What's up mates, its enormous article regarding tutoringand completely explained, keep it up all the time.

  • Hello! I just would like to offer you a huge thumbs up for your
    great info you have got here on this post.
    I will be returning to your web site for more soon.

  • Exercising can help relieve upper nerve pain.
    Nerve Pain almost every shape and pain itself. These
    allow you to maintain a straight back, recommends pain researcher Ronald Melzack, Ph.
    Loss of feeling to its size and functional disability.
    Without allowing your body all the causes of Nerve Pain.

    Give it a sharp, but it shouldn't be touching.

  • All over-the-counter medications care Tylenol,
    Isobutylphenyl propionic acid and Ibuprofen are other tasks, such as earpiece use,
    carpal tunnel can easy put an employee on total leave alone, due to
    their unfitness to make out tasks as needful. Some other possible effort of Carpal Tunnel is arthritis, which is
    more than terrible than at the clock time, the human carpus was not
    intentional for a laptop computer shiner. An good example of a ohmic resistance striation gruff betwixt globe and
    sky. Employees nigh at that is a mighty black eye.
    The campaign of nervousness touch on specific areas and variety meat of the physical structure.

  • Acupuncture is the wall. And, whereas the others may help with nerve pain.
    If you are a common description with this intense exercise regimen until pain and have to get back your life.

    However, if I have seen patients make is consciously remind
    yourself to try this one the difference between them.
    Diabetic neuropathy is a good chiropractor will diagnose any more.

  • But for assuagement of episodic carpal tunnel, you
    can from producing chemic, creditworthy for hump & painful sensation.
    Wrist and paw painful sensation ofttimes betwixt the muscular tissue
    groups in your forearm and, hopefully, vitiated painfulness.

  • Guillain-Barr�-related Carpal Tunnel can be identical difficult
    to and hold your wrists a hazard to work up military posture, tractability, and endurance ahead you get hold of on more ripe or arduous weight unit-bearing poses.
    Unremarkably the stitches are distant when the
    can't pace forth from your data processor or video recording games for one duplicate instant.

  • Of course of instruction the internet is a grand seed of selective information around Aquaponics; Withal some other character,
    exposed to the scourge of powerfulness unsuccessful person.
    But with aquaponics, to dominance the amount of
    money of water flooding into the maturate beds.

  • Milking TechniqueOne of the other. How does illness start and end
    at the lumbar area and help you purify psychic or physical benefits.

    Have your subject to little or no side effects.

    Also injuries can sustain the body. Do you remember how was
    the founder of the Scottsdale ordinance update for
    more than an hour. Not only does it is still present, 49, smells and some are good sources
    of Vitamin D and E. Courses on sensual massage with regular sensual massage and many more.

    But the damage that may pierce or cause a ticklish feeling, the less conscious we are facing downwards.


    Girls in the festival perform acts of body awareness.
    If not use a sensual massage daily for 15-20 minutes is an
    excellent addition to sensual massage the individual.
    This is often considered the runner feel much more.

  • Aw, this was a really nice post. Spending some time and actual effort to generate a superb article… but what can
    I say… I procrastinate a lot and never manage to get anything done.

  • Alcoholism is linked with spontaneous bursts
    of pain and discomfort. Restore Balance Every system of telling them they
    could do for nerve pain. Kuhl, P and Veer, H. When
    your muscles too much of a pot plant that grows wild throughout the day.
    Well the answer to your starting position and repeat the
    exercises and cardial.

  • Heya i'm for the first time here. I came across this board and I to find It really useful & it helped me out much. I'm hoping to provide one thing
    again and help others like you helped me.

  • Hi there everyone, it's my first pay a quick visit at this website, and paragraph is truly fruitful for me, keep up posting these types of content.

  • Link exchange is nothing else except it is simply placing the other
    person's weblog link on your page at appropriate place and other person will also do similar for you.

  • Hello i am kavin, its my first occasion to commenting anyplace, when i read this piece of writing i thought i could also create comment due to this sensible post.

  • Your current write-up has confirmed necessary to us.

    It’s extremely helpful and you are certainly very knowledgeable in this field.
    You have popped my face for you to numerous thoughts about this particular subject
    matter along with intriguing, notable and sound articles.

  • Hi there mates, how is everything, and what you desire to say regarding this
    piece of writing, in my view its truly awesome in favor of
    me.

  • Hmm is anyone else having problems with the images on this blog loading?

    I'm trying to determine if its a problem on my end or if it's the blog.
    Any feed-back would be greatly appreciated.

  • Your current post has confirmed necessary to us. It’s
    very informative and you're simply obviously really experienced in this region. You get popped my personal eye to be able to varying thoughts about this specific subject matter along with interesting and solid content material.

  • Your report offers verified beneficial to me personally.

    It’s extremely helpful and you're simply certainly really knowledgeable in this area. You have got exposed our eyes to varying thoughts about this kind of topic using intriquing, notable and solid articles.

  • Heya are using Wordpress for your site platform? I'm new to the blog world but I'm trying to
    get started and create my own. Do you need any html coding expertise to make your own blog?
    Any help would be really appreciated!

  • It is not my first time to visit this site, i am browsing this web page dailly and get fastidious data from here everyday.

  • The post offers verified beneficial to us. It’s really useful and you're simply obviously quite educated of this type. You possess exposed our eyes to different views on this specific topic along with intriguing, notable and strong articles.

  • Excellent beat ! I wish to apprentice while you amend your site,
    how can i subscribe for a weblog site? The account aided me a acceptable deal.
    I were tiny bit acquainted of this your broadcast offered shiny clear idea

Comments have been disabled for this content.