Thursday, December 30, 2010

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

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

No comments:

Post a Comment