Set focus on a clicked control in ASP.NET

Jan-Erik just blogged about how to set focus on a clicked control in an ASP.NET page. Sometimes you need to do that if the page you have is very, very long or if you have a list with vertical controls and you want to put focus on the clicked control after a postback. One way of doing it is to set focus in each and every control event (button1_clicked, button2_clicked) and so on. But what Jan-Erik is looking for is to put the focus-code in one place only.

Jan-Erik thought that his solution was a bit hacky and asked for another way of doing it, and I think I have a pretty simple one. The trick is to override the OnBubbleEvent() and check who the sender is. This seems to work pretty well:

protected override bool OnBubbleEvent(object sender, EventArgs e)

{

           if(sender is Button ||

                      sender is ImageButton)

           {

                      WebControl webControl = (WebControl)sender;

                      Debug.WriteLine("Clicked " + webControl.ClientID);

                      StringBuilder sb = GetFocusScriptBlock(webControl);

                      RegisterClientScriptBlock("FocusScript", sb.ToString());

           }

           return base.OnBubbleEvent(sender, e);

}

 

private static StringBuilder GetFocusScriptBlock(WebControl webControl)

{

           StringBuilder sb = new StringBuilder(1000);

           sb.Append("<script language = \"javascript\">");

           sb.Append("function ControlFocus() {");

           sb.Append("document.getElementById('" + webControl.ClientID + "').focus();");

           sb.Append("}");

           sb.Append(String.Concat(Environment.NewLine, Environment.NewLine, "window.onload = ControlFocus;"));

           sb.Append("</script>");

           return sb;

}

 

Any comments on this code? You think this is useful?

It may be good to know in what order the events happen in a Page:

1. Page_Load()
2. The specific event for the clicked control (Button1_Click() for example)
3. OnBubbleEvent()

No Comments