set the initialfocus for an asp.net webform the pageutil class has a static method setinitialfocus(control) which can be used to generate a javascript for an asp.net page (webform), which sets the focus on a (given) control.
private void page_load(object sender, system.eventargs e) { // set the initialfocus on textbox1 pageutil.setinitialfocus(textbox1);
using system; using system.web.ui;
namespace initialfocusdemo { /// <summary> /// utility class for a asp.net page /// </summary> public class pageutil {
/// <summary> /// set the intialfocus to the given control. only works when javascript is supported. /// </summary> /// <param name="control">control to set the initialfocus on.</param> public static void setinitialfocus(control control) { if (control.page == null) { throw new argumentexception("the control must be added to a page before you can set the intialfocus to it."); } if (control.page.request.browser.javascript == true) { control.page.registerclientscriptblock("initialfocus", "<script for='window' event='onload' language='jscript'>document.all." + control.uniqueid + ".focus();</script>"); } }