Set Input Focus on a Control Programatically Added to an ASP.Net Page

This little problem had the potential to drive me nuts for hours, I was fortunate to stumble over a blog with 100s of comments re problems of this nature and how to solve it. Most of the discussion was about using JavaScript, then I remembered I was using AJAX in my project and created a solution.

The Problem

I had a web page that automatically adds and removes TextBoxs based on a user's input e.g. a user may select "yes" in a DropDownList to a question and we need to get more information, so we add a Please Specify textbox on the postback of the DropDownList . But how on earth do you set the focus??

I tried adding the control to the page and then using its focus command, which didn't work.

AdditionalInfoTextBox.Focus();

Solution

Luckly I was using Ajax on the page and I had a ScriptManager in the MasterPage. The script manager pumps out JavaScript, so I used a method on it to set the focus of the control using its client ID. This is the unique ID it is given on the page.

ScriptManager mgr = (ScriptManager)this.Master.FindControl("ScriptManager1");

mgr.SetFocus(AdditionalInfoTextBox.ClientID);

Thank goodness for Google. I hope this helps you out..

Author Paul Marshall

A self confessed Microsoft bigot, Paul loves all Microsoft products with a particular fondness for SQL Server. Paul is currently focusing on Web 2.0 patterns and practices and is always looking for better ways of doing things.

I love the .net platform, and I find it to be the most productive toolset I have used to date.

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.