This article was contributed by Matthew Small and he can be reached at matt@showstopperonline.com
The Newbie Problem Part 1
OK, I am a newbie to Visual Basic.NET. However, I am an experienced programmer, and have used a few languages in my day, including VB 6.0 and C++. I therefore should be able to pick up the syntax of VB.NET pretty easily. Take this for example:
<asp:linkbutton commandname="categoryid" commandargument="1" oncommand="lbLink_Click" text="Men’s Clothing" />
|
The above is the explicit placement of a linkbutton on the webform. Logically, it should be equivalent to this code below:
dim lbLink as new LinkButton lbLink.Text = "Men’s Clothing" lbLink.CommandName = "CategoryId" lbLink.CommandArgument = "1" lbLink.OnCommand = "lbLink_Click" |
However, it is not. When run, this code will generate an error:
BC30390: 'System.Web.UI.WebControls.LinkButton.Protected Overridable Overloads Sub OnCommand(e As System.Web.UI.WebControls.CommandEventArgs)' is not accessible in this context because it is 'Protected'
Line 92: lbLink.Text = "Men’s Clothing" Line 93: lbLink.CommandArgument = "1" Line 94: lbLink.OnCommand="lbLink_Click" Line 95: Line 96: |
Ok, what does that mean? I really don’t know, but I do know that my code won’t work like that. The solution is simple but isn’t found in any of my ASP.NET books.
For reasons beyond my limited knowledge, Microsoft decided that instead of the logical dot-notation for adding a OnClick or OnCommand attribute to our Button, a separate statement was to be required: addhandler
dim lbLink as new LinkButton lbLink.Text = "Men’s Clothing" lbLink.CommandName = "CategoryId" lbLink.CommandArgument = "1" AddHandler lbLink.Command, AddressOf lbLink_Click |
The addhandler statement binds an event to a subroutine or function of your choice. The generic syntax is:
AddHandler event, AddressOf subroutine
For more detailed information on it, go to
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vastmAddHandlerStatement.asp
OK, that wasn’t so hard. We now have the correct syntax for binding an event to a subroutine or function.