Update 5/23/05: I posted a C# version of this code, and an additional method to allow enter directly from any textbox. This allows you to have the onEnter behavior using an ImageButton or no button at all. [Click here to view]
First, set focus to a control when a page loads,
Also, trigger the button's click event when hitting enter in a corresponding textbox.
I'm working in a VB.Net project, so I had to translate the C# version of the TieButtonToTextbox method from an article at allasp.net to VB.Net. Since I also needed a SetFocusToTextbox method, I also refactored the code out to create a GetFormName method that takes a control and returns the name of the parent form.
The methods below would be called from Page_Load like this: TieButton(Me.txtSearch,Me.btnGo), and SetFocus(Me.txtSearch)
Private Sub SetFocus(ByVal controlToFocus As Control)
Dim formName = GetFormName(controlToFocus)
Dim jsString As String = "
"
If Page.IsStartupScriptRegistered("SetFocusToSearch") = False Then
Page.RegisterStartupScript("SetFocusToSearch", jsString)
End If
End Sub
Private Sub TieButton(ByVal TextBoxToTie As Control, ByVal ButtonToTie As Control)
Dim formName As String = GetFormName(ButtonToTie)
Dim jsString As String = "if ((event.which && event.which == 13) || " & _
"(event.keyCode && event.keyCode == 13)) " & _
"{document." + formName + ".elements['" + ButtonToTie.UniqueID + "'].click();" & _
"return false;} else return true; "
If TypeOf ButtonToTie Is System.Web.UI.HtmlControls.HtmlForm Then
CType(TextBoxToTie, HtmlControls.HtmlControl).Attributes.Add("onKeyDown", jsString)
ElseIf TypeOf TextBoxToTie Is WebControls.WebControl Then
CType(TextBoxToTie, WebControls.WebControl).Attributes.Add("onKeyDown", jsString)
Else
Throw New ArgumentException("Control TextBoxToTie should be derived from either System.Web.UI.HtmlControls.HtmlControl or System.Web.UI.WebControls.WebControl", "TextBoxToTie")
End If
End Sub
Private Function GetFormName(ByVal sourceControl As Control) As String
Dim formName As String
Try
Dim i As Int16 = 0
Dim c As Control = sourceControl.Parent
Do While Not TypeOf c Is System.Web.UI.HtmlControls.HtmlForm And Not TypeOf c Is System.Web.UI.Page And i < 500
c = c.Parent
i = i + 1
Loop
If TypeOf c Is System.Web.UI.HtmlControls.HtmlForm Then
formName = c.ClientID
Else
formName = "forms(0)"
End If
Catch ex As Exception
formName = "forms(0)"
End Try
Return formName
End Function
Print | posted on Thursday, August 26, 2004 6:24 PM