Wednesday, September 2, 2009

Default Focused Control Asp.net

When developing the web application it is good idea that when form open then it should be set the focus to the some control. For example if you have user log-in form then it is nice if you set the focus on the user log-in name when form loaded. In this post I will show you the techniques used to set the default focus on control when control is first loaded.

First Way
:
With the release of the ASP.NET 2.0, the problem of making the default focus of the control is much easier with the introduction of the "default button" property of the form. Now you can use the defaultfocus attribute of the form. Here is sample HTML code that contains for the form :

<form defaultfocus="ControlID" runat="server">
With the above html code you can set the default focus control for the form. ASP.NET 2.0 provides three different new solutions if you need to set focus dynamically. At run time you can use Page.SetFocus method with control's ID as a parameter or you can simply call a new control's Focus method. They both do practically the same thing. It is only programmer's choice to choose which method likes more.

Second Way
In the second way of achieving default focus control functionality is the JavaScript way and below is the JavaScript code which is used to set the default focus control for the page. Here I have a simple function named "onBodyLoad" which is used to set the focus on the control when form is loaded.
function onBodyLoad()
{
var txtLoginName=document.getElementById('<%= txtLoginName.ClientID%>');
if(txtLoginName !=null)
txtLoginName.focus();
}
The above function can be called at body load or at the form load event, which is set the focus on the control.

Note :When using the master page in asp.net form, when you add new form in your application and check the option of selecting the master page , the newly added form don't have form or body tag it only contain asp:content control which don't have any onload event like the form and body have, so you can either use Page.SetFocus or control.Focus property.

You can download the source code from here.

Note : The download source only contain the JavaScript function .


All and any comments / bugs / suggestions are welcomed!


No comments: