Prashant Kulkarni Prashant Kulkarni - 2 months ago 5
Vb.net Question

Open different forms on different button click in VB.NET

A noob query I have, is there any way to use a single command to open different forms on different button click events. I have 24 buttons in one form and will use these buttons to open 24 different forms.

So instead of doing it for 24 times as:

Private Sub BtnCh1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCh1.Click
FormCh1.Show()
End Sub
Private Sub BtnCh2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCh2.Click
FormCh2.Show()
End Sub
Private Sub BtnCh3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCh3.Click
FormCh3.Show()
End Sub
Private Sub BtnCh4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCh4.Click
FormCh4.Show()
End Sub


Can it be done with a single command?

Answer

In your form's load event add the forms in a List(Of Form)

Private list As List(Of Form)
Private Sub Me_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
    list = New List(Of Form)
    list.Add(New Form1())
    '
    '
    '
    list.Add(New Form24())
End Sub

Set your button's Tag property with the form's index and set them all to use the same click event:

Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click
    list(CType(sender, Button).Tag).Show()
End Sub