Wednesday, December 5, 2012

Two Ways of Handling Events in the DataGrid WebControl

The DataGrid WebControl allows you to use two ways to handle events. The first method is to specify the event handler as a property of the DataGrid on the aspx page itself.

<asp:DataGrid ID="dgTest" OnEditCommand="dgTest_EditCommand">

Or you can define a subroutine on the aspx.vb file with a Handles keyword.

Private Sub dgTest_EditCommand(ByVal source As Object, ByVal e As

  System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgTest.EditCommand

In most cases, you want to only use one or the other, but what happens if you use both for the same DataGrid? Visual Studio 2008 will certainly allow you to do this. If the same handler is specified in both places, the handler is called as expected, as if it was only wired in one place. I think this situation should be avoided as it can easily cause unintended consequences later, such as if the developer decides to change or delete the handler in one place and forgets to make the same change on the other. If different handlers are wired in both places, the handler(s) defined in the aspx.vb file will be called first, after which the handler specified on the DataGrid control will be called. The other thing to know is that the handler wired in the DataGrid tag must be declared as protected or public.

I prefer to always wire the handlers inside the aspx.vb file only. This way, any changes to the handler, including something as simple as changing the name of the handler, can be done on the vb file without having to change the aspx file. This also allows you to wire multiple handlers for the same event. Lastly, this also has the advantage of allowing you to define the handler as private, which is what VS 2008 uses by default when it generates the handler for you.