Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get Form by Name

Tip of the Day

Get Form by Name

by  SBendBuckeye  Posted    (Edited  )
This is a form equivalent to Get control by name using reflection faq796-5698 written by Chrissie1 a while ago.

I wanted to be able to create a form instance from the form name itself. Thanks to some threads on this forum, a bit of Googling and some MSDN work, I was able to come up with the following code. Enjoy!
Code:
Imports System.Reflection
Imports System.windows.forms

'Creates form from form name - CASE SENSITIVE
Public Shared Function GetFormByName( _
    ByVal formName As String) As Form

    Dim assemblyName As String = _
        [Assembly].GetEntryAssembly().GetName.Name.Replace(" ", "_")
  
    Dim myType As Type = _ 
        Type.GetType(assemblyName & "." & formName)
  
    Return CType(Activator.CreateInstance(myType), Form)

End Function

Another way was sent to me by chrissie1
Code:
Private Function GetFormByName(ByVal formName As String) As Object

    Dim myasm As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()

    Try
        Return myasm.CreateInstance(myasm.GetName.Name.Replace(" ", "_") & "." & formName)

    Catch ex As Exception
        Return Nothing
    End Try

End Function
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top