CraigWardman.com

[ Programmatically Setting the Default Button of a Textbox ]

/Blog/Post

A catalogue of my discoveries in software development and related subjects, that I think might be of use or interest to everyone else, or to me when I forget what I did!

Programmatically Setting the Default Button of a Textbox

Thursday, 9 October 2008


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:


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

Labels: , ,

Share This!



0 Comments:

Post a Comment

<< Home

CraigWardman.com