Tutorial :ASP.NET Click Event Handle - How to pass an argument in VB.NET?



Question:

I'm using the accordion Ajax control. For each Accordion pane I have text and a Button dynamically created. When the user fires the click event I want to know what button in which pane was fired. So I want to handle the button's click event in a way that I can send the ID (probably by event args) to the event handler in order for the handler to know what to do according to the button that was pressed.

I know I have to do something like this:

AddHandler bGetSessionMembers.Click, AddressOf bGetSessionMembers_click  

but I whanted to do something like this:

AddHandler bGetSessionMembers.Click, AddressOf bGetSessionMembers_click(Me, "My ID")  

I think you can do that in C#

bGetSessionMembers.Click += bGetSessionMembers_click(Me, "My ID")  

or even in C# but with anonimous delegates.

Does anyone have a clue?


Solution:1

Here is a better way to do this. First, wire up your buttons like normal:

AddHandler Button1.Click, AddressOf Click  AddHandler Button2.Click, AddressOf Click  

Then create a Click method like this:

Sub click(ByVal o As Object, ByVal e As EventArgs)      Dim button As Button = TryCast(o, Button)          If button IsNot Nothing Then        End If  End Sub  

Inside that if statement you now have a Button - you can grab its ID or anything else about it that you'd like.

Edit in response to comment:

I think you may be misunderstanding how events are wired up in .NET. When you do this:

AddHandler Button2.Click, AddressOf Click  

You are not calling the method Click, you are passing a delegate to a compiler-generated method for the Button.Click event that adds your delegate to a delegate invocation list. When the Button raises its Click event your delegate is invoked by the Button.

Since you will not be the one to invoke the method via the delegate you cannot change what gets passed in. Your best option is to use the Object that is passed to you and cast it to a Button like I did above.


Solution:2

Andrew's answer is superb, and exactly what I'd do. I'd just like to add to the code snippet he wrote, because that blank line looks like it is crying out for a snippet showing how to use the CommandArgument and CommandName properties of System.Web.UI.Button:

Sub click(ByVal o As Object, ByVal e As EventArgs)      Dim button As Button = TryCast(o, Button)          If button IsNot Nothing Then          Select Case button.CommandName            Case "Command1"              'Your cool feature here :)            Case "Command2"              'You could check button.CommandArgument to get additional data            Case Else              'Runs if button.CommandName isn't handled by your code          End Select      End If  End Sub  

Andy - hope you don't mind me throwing some more stuff in here :)

HTH,

Richard.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »