How to set the focus to the master page controls

While web development using ASP.NET, we often required to set the focus of your page pointing to particular controls. We can use Page.SetFocus(Control) or Page.SetFocus(“Contol.ClientID”) to do bring the focus to the respective control after an operation.

Let us consider a scenario of implementing custom pagination controls, set to display 50 records in each page. When you press the previous or the next button, the focus will be pointing to the end of the page. In order to improve the user-friendliness, we can include Page.SetFocus(Control) after binding the grid. Note that the Control here need to be replaced by any controls that are present in to top of your pages.

When it comes to the master pages, the above method will not give us the required result, rather it will ignore the Master page and focus will be displaying the first line of your child page. In order to set the focus to the MasterPage, an additional piece of code need to add, as shown below:

Consider I have a log out label of id “lbtnLogout” in the top of the master page.In order to set the focus to the beginning of the page, I need to make use of the topmost control in the Master Page. The code for the same is :

LinkButton userName = (LinkButton)Master.FindControl(“lbtnLogout”); 

//use the find control in-built method to fetch the lbtnLogout control’s client ID in Master Page

Page.SetFocus(userName.ClientID);

 

This will set the focus to the master page controls. Hope it Helps! Happy Learning folks!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s