Set Focus using Access Keys ( like ALT+A)

« View all ASP.net articles

February 05, 2207

Related Content
• Set Focus to a TextBox Control
• Default Button - Click Enter Key to Activate

There are instances when you want to set focus to a TextBox or ListBox using an Access Key. There are 2 ways of achieving this.

METHOD 1: Use the AccessKey property of the form tag.

In this example I set the AccessKey property of the txtFirst TextBox to S using the AccessKey property of the form tag.When you press ALT+S, the TextBox will get focus.

<form id="frmFocus" AccessKey="s" runat="server">
   <asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
   <br /><br />
   <asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
</form>

METHOD 2: Code behind using the AccessKey property
In the Page_Load event define the AccessKey property for the control that you want focus to be when the access key (ALT+letter) is pressed .

In this example, I once again set focus on the txtFirst textbox when ALT+S is pressed.

This is the form
<form id="frmFocus" runat="server">
   <asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
   <br /><br />
   <asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
</form>
This is the code behind for page_load event
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   txtFirst.AccessKey = "s"
End Sub
Both methods add the accesskey property for the input tag:

<input name="txtFirst" type="text" id="txtFirst" accesskey="s" />
Further Reading
How to: Set Access Keys for ASP.NET Web Server Controls