Set Focus to a TextBox Control

« View all ASP.net articles

February 05, 2007

Related Content
• Set Focus using Access Keys ( like ALT+A)
• Default Button - Click Enter Key to Activate

There are 2 ways to set focus to a TextBox Control. One uses the defaultfocus property of the form tag and the other uses the SetFocus method in the code behind.

METHOD 1: defaultfocus property of the form tag.
Set the defaultfocus property of your form tag to the TextBox control that you want focus to be when the page loads.

In this example, I set the txtSecond TextBox to get the focus.
<form id="frmFocus" defaultfocus="txtSecond" runat="server">
   <asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
   <br /><br />
   <asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
</form>
Using the above method, ASP.net automatically generates the javascript code similar to this:

<script type="text/javascript">
<!--
var theForm = document.forms['frmFocus'];
if (!theForm) {
theForm = document.frmFocus;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
// -->
</script>
<script src = "/meLearnASP/WebResource.axd?d=h-3ozB6yE7kktukwzb35jQ2&amp;t=632962808772500000" type="text/javascript"> </script>

<script src = "/meLearnASP/WebResource.axd?d=877-R4s79zcEtvRxKhoRpQ2&amp;t=632962808772500000" type="text/javascript"> </script>

<script type="text/javascript">
<!--
WebForm_AutoFocus('txtSecond');// -->
</script>

METHOD 2: Code behind using the SetFocus property
In the Page_Load event define the SetFocus property for the TextBox control that you want focus to be when the page loads.

In this example, I once again set the txtSecond TextBox to get the focus.


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
   Me.SetFocus("txtSecond")
End Sub
Using the SetFocus in the code behind method, ASP.net generates the same javascript code as using the defaultfocus property of the form tag.