Declare and Define an Object Dynamically

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • almisba7
    New Member
    • Nov 2008
    • 7

    #1

    Declare and Define an Object Dynamically

    Hi,
    I have the following situation, can anybody help me in that?

    Following is a "pseudo" code of what I want to do in VB using VB.NET 2005:

    In my main form I have the following
    Code:
    'Code Begins
    Dim vCurrentForm As Form
    
    Private Sub CallCurrentForm (ByVal pForm as String) 
       If vCurrentForm Is Nothing OrElse vCurrentForm.IsDisposed Then
          vCurrentForm = <# New pForm #>
          vCurrentForm.MdiParent = Me
       ElseIf Not TypeOf vCurrentForm Is <# pForm #> Then
          vCurrentForm.Close()
          vCurrentForm = <# New pForm #>
          vCurrentForm.MdiParent = Me
       End If
       vCurrentForm.Show()
    End Sub
    'Code Ends
    Where I am calling 'CallCurrentFor m' everywhere in my menu just by passing the proper form name as a string
    example: CallCurrentForm ("AddNewAccount ")

    My problem is how to do the code between <# ... #>

    Thanks,

    Samantha
    Last edited by pbmods; Apr 19 '09, 05:45 PM. Reason: Added CODE tags.
  • aryanbs
    New Member
    • Mar 2009
    • 42

    #2
    Are you looking for something like this?

    Anyway, you can find out from below

    Make sure you have added following Imports line
    Imports System.Reflecti on

    Code:
    Private Sub CallCurrentForm(ByVal pForm As String)
            'look whether form is already opened
            For Each openedform In Me.MdiChildren
                If openedform.Name = pForm Then
                    vCurrentForm = openedform
                    vCurrentForm.Show()
                    Exit Sub
                End If
            Next
            'if not found create new one
            Dim objForm = Assembly.GetExecutingAssembly.CreateInstance(Assembly.GetExecutingAssembly.GetName.Name & "." & pForm)
            vCurrentForm = CType(objForm, Form)
            vCurrentForm.MdiParent = Me
            vCurrentForm.Name = pForm
            vCurrentForm.Show()
        End Sub
    Uses
    CallCurrentForm ("Form2")

    Comment

    • almisba7
      New Member
      • Nov 2008
      • 7

      #3
      Thanks, it did the trick with one extra IF statement.

      I just add the following IF statement just before the FOR loop:

      Code:
      If Not vCurrentForm Is Nothing AndAlso Not vCurrentForm.IsDisposed AndAlso vCurrentForm.Name <> pForm Then
          vCurrentForm.Close()
      End If
      The idea is to have only one form open at a time.

      Thanks again.

      Comment

      Working...