As a developer, repetitive code is your enemy. It takes longer to write, leads to
larger files, and is harder to maintain. I was recently sent a piece of code that
looked something like this:
<script runat="server">
Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
MultiView1.SetActiveView(View1)
End Sub
Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
MultiView1.SetActiveView(View2)
End Sub
Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
MultiView1.SetActiveView(View3)
End Sub
...
</script>
That doesn't seem like a big deal until I tell you that the "..."
in the listing above actually continued for about a dozen more buttons!
Which brings me to the point of this tip. Did you know that you can tie
the same event handler to multiple objects? It's easy to do, but most people
just never think to try it.
Instead of the code above you'd end up with just one Sub. Granted
the code in that Sub would be a little more complex since it would need to
determine which Button object you clicked, but overall you'd still end up with
less code and more importantly, code which is easier to extend and maintain.
The magic that allows us to do this is the fact that event handlers
take a standard set of two parameters: the object which raised the event ("sender") and
an object containing event information ("e"). By examining the values of these
parameters we can determine how the event was raised. In our example above we simply
need to need to determine which button the user clicked. We can easily get this
information by retrieving the "ID" property of the "sender" object.
After that it's just a matter of showing the appropriate view.
Not wanting to leave you hanging I actually went ahead and wrote the alternative code.
It's a little uglier then I'd like, but the same code will handle all the buttons.
Simply set each button's "OnClick" property to "Button_Click"
instead of creating a new Sub for each button.
<script runat="server">
Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim intButtonId As Integer
' Get button number. Buttons are named "Button1", "Button2",
' "Button3", etc. so we get the text starting at the 7th character.
' The number below is 6 because things are zero-based.
intButtonId = CInt(sender.Id.ToString.Substring(6))
' Show the View corresponding to the Button the user clicked.
' Again we take one off to compensate for the fact that Views
' are numbered starting at zero.
MultiView1.SetActiveView(MultiView1.Views.Item(intButtonId - 1))
End Sub
</script>
If you have a tip you would like to submit, please send it to:
webmaster@asp101.com.