http://www.sqlservercentral.com/blogs/nycnet/2010/12/30/wiring-up-a-common-click-event-handler-in-an-asp.net-page/

Printed 2014/10/21 04:38AM

Wiring up a common click event handler in an ASP.NET page

By nycdotnet, 2010/12/30

I was just refactoring a server-side control and ran into some horrible code.  Basicaly there was a big listbox that was supposed to hold people's names with letters A through Z to the left which were ASP.NET LinkButtons.  lnkBtnA, lnkBtnB, etc.  Each link button had its own click handler whose code only differed by the letter that would be used to filter the listbox.  Of course, since I needed to change how the filter worked, I would have had to make 26 edits to each of the subroutines.  Instead, I deleted them all and wrote the following:

Note: RegisterClickEvents() has to be called in the Page_Init event, as Page_Load is too late in the cycle.


Private Sub RegisterClickEvents()
 For Each objControl In Me.Controls
  If TypeOf objControl Is System.Web.UI.WebControls.LinkButton Then
   If InStr(DirectCast(objControl, System.Web.UI.WebControls.LinkButton).ID, "lnkBtn", CompareMethod.Text) > 0 Then
    AddHandler DirectCast(objControl, System.Web.UI.WebControls.LinkButton).Click, AddressOf FilterLinkButtonClick
   End If
  End If
 Next
End Sub



Protected Sub FilterLinkButtonClick(ByVal sender As Object, ByVal e As EventArgs)
 'Find the letter from the ID of the control that was clicked so we know what to filter by
 Dim strFilterLetter As String
 strFilterLetter = Replace(UCase(DirectCast(sender, System.Web.UI.WebControls.LinkButton).ID), "LNKBTN", "")
  
 '... other code to do the filtering on my listbox

End Sub


Copyright © 2002-2014 Simple Talk Publishing. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.