Public Shared Sub SetDefaultButton(ByVal textbox As System.Web.UI.WebControls.TextBox, ByVal button As System.Web.UI.WebControls.IButtonControl)
If TypeOf button Is System.Web.UI.WebControls.WebControl Then
textbox.Attributes("onkeypress") = "javascript:if (event.keyCode == 13){ document.getElementById('" & CType(button, System.Web.UI.WebControls.WebControl).ClientID & "').click();event.cancelBubble = true;if (event.stopPropagation) event.stopPropagation();return false;}"
End If
End Sub
- Published on
Programmatically Setting the Default Button of a Textbox
- Authors
- Name
- Craig Wardman
In ASP.NET, setting the default button of a textbox is usually a simple task as you simply wrap the button and textbox in an asp:panel and set the 'defaultbutton' attribute on the panel.
Sometimes however, it is not possible to put the button and textbox in a panel together, for example if the textbox is part of a databound template (e.g. gridview, repeater etc.)
If you look at the HTML code that the asp:panel method generates, it basically attaches a javascript event handler to the 'onkeypress' of the textbox.
I have wrapped this functionality, so that you can programmatically set the default button of any textbox control on your page, to any button on your page.
Code: