You are not Logged in
Would you like to Login or Register

Today is: Wednesday, 03 December, 2008
Check this months hot topics

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..

kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Marshall Skype
Author : Paul Marshall
Published : Saturday, 01 December, 2007

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

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views