Search code examples
vb.netoopaddressof

vb.net runtime buttons and "AddressOf " parenthese


in my system i am creating runtime buttons, i have create one sub to create all buttons which is fine for what i need however they all go to the same "addressOf" i want to create separate handlers, however it doesnt allow with my current method any one know a simple workaround id prefer not to change the actual structure that i have, thanks


sorry dont know why this part is being weird

private Sub Button(ByVal x As Integer, ByVal y As Integer, ByVal name As String, ByVal title As String, ByVal hieght As Integer, ByVal width As Integer, ByVal buttonAddress As String)

    Dim btn As Button
    btn = New Button

    With btn
        .Location = New Point(x, y)
        .Text = title
        .Name = name
        .Width = width
        .Height = hieght
        Controls.Add(btn)

        AddHandler btn.Click, AddressOf "BtnOperation_" & buttonAddress

  End With

End Sub


Public Sub BtnOperation_AddAppointment(ByVal sender As Object, ByVal e As EventArgs)
    Dim btn As Button = DirectCast(sender, Button)
    Dim name = btn.Name

    Select Case name

        Case "Cfind_Btn"
            'when the Cfind_btn is pressend it create a Csearch textbox at runtime 
            btn.Visible = False
            GetFormType("add_CfindOK")
            CreateTxtTypeBox(BoxType.Combo_box, "CSearch_Box")

        Case "add_CfindOK"


        Case ("Cnew_Btn")
            'open the add customer form that connects to the mysql database'
    End Select
    'fetch the btn.name'
    ' then with the name use "select case" to get appropreate action of the btn. ' 

End Sub

Solution

  • Pass the handler into your Button factory method:

    private Sub Button(ByVal x As Integer, ByVal y As Integer, ByVal name As String, ByVal title As String, ByVal hieght As Integer, ByVal width As Integer, 
        clickHandler As System.EventHandler)
    
        Dim btn As Button
        btn = New Button
    
        With btn
            .Location = New Point(x, y)
            .Text = title
            .Name = name
            .Width = width
            .Height = hieght
            Controls.Add(btn)
    
            AddHandler btn.Click, clickHandler     
      End With
    
    End Sub
    

    Then, when you call Button use AddressOf to pass in the correct handler:

    Button(0,0,"MyButton".....,AddressOf BtnOperation_AddAppointment)