0

How I call generic Of T sub choose form string?
How to better way code like this?

Sub ShowAddfrm(Of T As {Form, New})()
     dim frm as new T 'New Form
     frm.Show()
End Sub
Private Sub btnAddProblemfrm_Click(sender As Object, e As EventArgs)
    Dim keys As String = CType(sender, Button).Name.Replace("btnAdd", "")

    If keys = "frmShowProblem" Then
        ShowAddfrm(Of frmShowProblem)()
    End If

    If keys = "frmUser" Then
        ShowAddfrm(Of frmUser)()
    End If
End Sub
Dome
  • 59
  • 5

1 Answers1

0

Try this overloaded method, allowing both a Form reference and string parameter.
You can pass the default instance of a Form, naming it directly:

ShowAddfrm(Form2)

or the Form's name:

ShowAddfrm("Form2")

or using a Control's Tag property (or any other source) in an event handler:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ShowAddfrm(DirectCast(sender, Control).Tag.ToString())
End Sub

There's a difference:

  • if you use pass the instance of a Form, only that instance will be created. Meaning, if you use a Button to show the Form and you press the Button multiple times, no new instances will be created. If you close the Form, then a new instance will be shown.
  • If you use the string version, each time you call this method, a new instance of the Form will be shown, so you can have multiple Forms on screen.

The string version uses Activator.CreateInstance to generate a new instance of a Form using it's name.

Sub ShowAddfrm(Of T As {Form, New})(ByVal form As T)
    form.Show()
End Sub
Sub ShowAddfrm(formName As String)
    Dim appNameSpace = Assembly.GetExecutingAssembly().GetName().Name
    Dim form = CType(Activator.CreateInstance(Type.GetType($"{appNameSpace}.{formName}")), Form)
    ShowAddfrm(form)
End Sub
Jimi
  • 29,621
  • 8
  • 43
  • 61