One of the small irritants in the ASP.NET framework is there is no built-in mechanism to set the focus of a control directly in code - you have to emit javascript to handle the job for you.
This is no problem, as ASP.NET gives you standard methods that allow you to register client script blocks with a page, but most of the solutions I've seen to this problem so far involve adding code directly to the inherited Page object to do the job.
However, this to me is untidy and as it's a common enough function to want to achieve, it would be nice to have a component you can quickly drop onto your page.
The code that follows does exactly that; once added to your toolbox, you can drop this component onto your ASP.NET design surface. From the properties box, simply set the ControlToFocus property to the control you want to, er, focus.
It works by handling the target controls' PreRender event, and injecting a startup script into the associated Page object. Very, very simple.
using System;using System.ComponentModel;using System.Web.UI;namespace EdCourtenay.Community.WebControls{ public class FocusSetter : Component { private Control focusControl = null; public FocusSetter() {} public Control ControlToFocus { get { return focusControl; } set { if (focusControl != null) focusControl.PreRender -= new EventHandler(FocusControlPreRender); focusControl = value; if (focusControl != null) focusControl.PreRender += new EventHandler(FocusControlPreRender); } } private void FocusControlPreRender(object sender, EventArgs e) { Control control = (Control)sender; Page page = control.Page; if (page != null) { string script = String.Format("<script type=\"text/javascript\">document.getElementById(\"{0}\").focus();</script>", control.UniqueID); page.RegisterStartupScript("focusControl", script); } } }}
Remember Me
dasBlog theme by Mads Kristensen
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.