Results 1 to 8 of 8

Thread: [RESOLVED] Instantiate a Form by it's name

Hybrid View

  1. #1

    Thread Starter
    Fanatic Member simonm's Avatar
    Join Date
    Sep 2000
    Location
    Devon, England
    Posts
    796

    Re: [2005] Instantiate a Form by it's name

    Basically, I have table which there will be a variable number of alternative data entry forms. These will be stored in a table and the User's chosen form will be the data entry form that is instantiated when they wish to edit a record.

    Sure, I could just have a SELECT CASE statement but I thought this would be a more elegant way of doing it...?
    Everything I say is either loose interpretation of dubious facts or idle speculation rooted in irrational sentiment.

  2. #2
    PowerPoster
    Join Date
    Jul 2002
    Location
    Dublin, Ireland
    Posts
    2,148

    Re: [2005] Instantiate a Form by it's name

    OK - this can be done thus:-
    VB Code:
    1. Imports System.Reflection
    2.  
    3. Public Class FormUtilities
    4.  
    5.     ''' <summary>
    6.     ''' Loads a new instance of the form passed in
    7.     ''' </summary>
    8.     ''' <param name="Formname"></param>
    9.     ''' <remarks></remarks>
    10.     Public Shared Function InstantiateFormByName(ByVal Formname As String) As Form
    11.  
    12.         Dim FormType As System.Type
    13.         '\\ Find the type that corresponds to the form name passed in
    14.         For Each f As Type In Assembly.GetExecutingAssembly.GetExportedTypes
    15.             If f.Name = Formname Then
    16.                 FormType = f
    17.                 Exit For
    18.             End If
    19.         Next
    20.         If Not FormType Is Nothing Then
    21.             '\\ Get th econstructor that has no parameters
    22.             Dim ctor As System.Reflection.ConstructorInfo = FormType.GetConstructor(System.Type.EmptyTypes)
    23.             Return CType(ctor.Invoke(Nothing), Form)
    24.         End If
    25.  
    26.     End Function
    27.  
    28. End Class

    and an example ofd the usage is:-
    VB Code:
    1. Dim fSettings As Form = FormUtilities.InstantiateFormByName("SettingsDialog")
    2.         fSettings.ShowDialog(Me)

    This was rather hastily knocked together so there's not enough error handling or optimisation but it shows how you can do it...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width