Default focus and default button in

Sometimes ago a friend ask me how to put default focus and default button in ASP.NET. He was not knowing that there is property for that in form tag in I thought it will be good idea to write a blog post about that.So those who are not aware of this feature can get an idea for that.

In some cases we need to have default button and default focus. For example take a example of a shopping cart registration form. Where you need to have default focus into the first textbox if you contain list of textboxes over there. Same way you can have more then one button on forms for example save and cancel so once user press enter which button should be pressed. On above both scenario this Default button and default features can come very handy.

From 2.0, The form tag has this two properties DefaultButton and DefaultFoucs where you can set the Id of control that you need as default button and same way you need to put Id of a control for default focus.

So what we are waiting for I have created following example.

<form id="form1" runat="server" DefaultButton="btnSave" DefaultFocus="txtFirstName">
       <p>First Name:<asp:TextBox runat="server" ID="txtFirstName"></asp:TextBox></p>
       <p>Last Name:<asp:TextBox runat="server" ID="txtLastName"></asp:TextBox></p>
            <asp:Button runat="server" ID="btnSave" Text="Save"/>
            <asp:Button runat="server" ID="btnCancel" Text="Cancel"/>

Here i have taken two button and two textbox to demonstrate the things. Now when you run this in browser it will look like following.


Here you can see the default cursor is there in firstname box and when you press enter save button click will fired.

Hope you like it. Stay tuned for more.

Shout it


Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Creating PDF with ASP.Net MVC and RazorPDF

Solution: gulp is not recognized as internal or external command- Visual Studio