Setting Controls Focus in ASP.NET

You are currently viewing Setting Controls Focus in ASP.NET

One of the very important features of current successful websites is providing better user experience to the users. As a developer you need to make sure that your website user interface is simple and easy to use. One way you can achieve this is by providing better focus management of your controls. Controls such as textboxes, listboxes or drop down lists should get focus automatically at the page load time to save user time on extra mouse clicks.

ASP.NET 2.0 provides three different ways you can set focus on any control in your page.

Set Focus using defaultfocus attribute of Web Form

<form id="Form1" runat="server" defaultfocus="TextBox1">
    <asp:TextBox id="TextBox1" runat="server" />
    <asp:TextBox id="TextBox2" runat="server" />
    <asp:Button id="Button1" runat="server" text="Button1" />
</form>

Set Focus using Page.SetFocus() method

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Page.SetFocus(TextBox1);
End Sub

Set Focus using Focus() method of Controls

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    TextBox1.Focus();
End Sub

READ ALSO:  Formatting GridView output based on Data

Leave a Reply