Search code examples
vb.netbasic

How to call a function that requires a value on the click of a programmatically added button in VB?


I need to call a function and return the text of the button that is added though the button is programmatically added. For example

AddHandler button.Click, AddressOf function(value)

Thought that isn't possible because of the following reason:

Error 1 'AddressOf' operand must be the name of a method (without parentheses).


Solution

  • Using a lambda-expression is fine, you however have to write it correctly. You do not use the AddressOf operator. A Click event handler is a Sub, not a Function. It requires two arguments. So proper syntax is:

        AddHandler button.Click, Sub(sender, e)
                                     MessageBox.Show("Clicked!")
                                     Dim retval = SomeFunction(value)
                                     '' etc...
                                 End Sub
    

    VS2010 or higher required.