# VB.NET _Click sub for dynamically created buttons?



## tim8w (Nov 9, 2004)

I have a form where I have added buttons to by calling MyMsgBox.Controls.Add(NewButton).

How do I write the Click sub?

Calling Routine:


```
Dim MyMsgBox As New dlgMessageBox
        Dim NewButton As New Button

        NewButton.Text = "New"
        MyMsgBox.Controls.Add(NewButton)
```
dlgMessageBoxRoutine:


```
Public Class dlgMessageBox

    Public Function ShowForm() As Integer
        Me.ShowDialog()
     End Function

    Private Sub cmdButtonCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdButtonCancel.Click
        Me.Close()
    End Sub

End Class
```
How do I write the _Click routine for the new button I added?


----------



## tim8w (Nov 9, 2004)

With help from Athiest in another forum, here's the solution:

Calling routine:


```
Dim MyMsgBox As New dlgMessageBox
        Dim NewButton As New Button
        Dim ReplaceButton As New Button
        Dim AppendButton As New Button
        Dim iButtonClicked As Integer

        NewButton.Text = "New"
        NewButton.Tag = 1
        MyMsgBox.Controls.Add(NewButton)
        ReplaceButton .Text = "Replace"
        ReplaceButton .Tag = 2
        MyMsgBox.Controls.Add(ReplaceButton )
        AppendButton .Text = "Append"
        AppendButton .Tag = 3
        MyMsgBox.Controls.Add(AppendButton )


        iButtonClicked  = MyMsgBox.ShowForm()
```
dlgMessageBoxRoutine:


```
Public Function ShowForm() As Integer
        Dim iIndex As Integer

        For iIndex = iLastOriginalControl To Me.Controls.Count - 1
            AddHandler Me.Controls.Item(iIndex).Click, AddressOf ButtonClicked
        Next iIndex
        Me.ShowDialog()
        ShowForm = iButtonClicked
    End Function

    Private Sub ButtonClicked(ByVal sender As System.Object, ByVal e As System.EventArgs)

        iButtonClicked = sender.Tag
        Me.Close()
    End Sub
```


----------

