Focus after postback in ASP.Net with VB.Net

October 5th, 2009

I’ve been trying to set focus to a textbox control in vb.net after a postback event. It’s a typical scenario where I wanted to check a BSN number against a database and perform actions based on whether the BSN was found or not. The application uses the Java toolbox and .Net 2.0, but for some reason the ScriptManager.SetFocus does not produce the desired result; focus is not set to the textbox below the BSN number textbox, but after the postback focus is set on the form. Very annoying and confusing.

Looking for a solution, I stumbled onto Ryan Farley’s blog. One of his ancient posts deals with this problem and provides a solution using programatically produced Javascript. The original post uses C#, but below is my VB.Net implementation.

The Sub SetFocusTo takes a control as parameter and produces the javascript that sets focus to that control on the Onload event of the window. Call this sub with the name of the control you want to set focus to after going through the postback-code, and you’re done!

Public Sub SetFocusTo(ByVal p_objControl As Control)
   Dim l_objStringBuilder As New StringBuilder()

   l_objStringBuilder.Append("<script language=’JavaScript’>" + vbCrLf)
   l_objStringBuilder.Append("<!–" + vbCrLf)
   l_objStringBuilder.Append("function SetFocus()" + vbCrLf)
   l_objStringBuilder.Append("{" + vbCrLf)
   l_objStringBuilder.Append(vbTab + "document.")

   Dim l_objParentControl As Control = p_objControl.Parent
   While Not TypeOf l_objParentControl Is _
                           System.Web.UI.HtmlControls.HtmlForm
      l_objParentControl = l_objParentControl.Parent
   End While

   l_objStringBuilder.Append(l_objParentControl.ClientID)
   l_objStringBuilder.Append("['")
   l_objStringBuilder.Append(p_objControl.UniqueID)
   l_objStringBuilder.Append("'].focus();" + vbCrLf)
   l_objStringBuilder.Append("}" + vbCrLf)
   l_objStringBuilder.Append("window.onload = SetFocus;" + vbCrLf)
   l_objStringBuilder.Append("// –>" + vbCrLf)
   l_objStringBuilder.Append("</script>" + vbCrLf)

   p_objControl.Page.RegisterClientScriptBlock("SetFocus", _
                           l_objStringBuilder.ToString())
End Sub
 

Uncategorized | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
You can keep track of new comments to this post with the comments feed.

About me

My name is Marco Hokke. My blog is about the things that interest me and things I might forget if I would not blog them.

Some of my favourite things are coding, photography, beer, theater and dance, Brian Eno's ambient music, Rammstein, purple, and reading.

Archives

Blogroll

Comics

Sites

Rijksmuseum

Meta