Visual Basic 2008 declaring FORM object from Strin variable

Hi I have been trying all sorts of ways to set a FORM object variable that is derived from a String rtrived from a database.

I use this method to load specific start modules depending on the Group name.

The code below gives me the following error:
Could not load type 'MyProj.MainDBPiForm' from assembly 'My Project, Version=1.1.4.25, Culture=neutral, PublicKeyToken=null'.

The variable FormName returns the propper output including the dot that represents project.form

don't know what to do from there.. :(

Can anyone help or suggect a better method ?

Dim frm As Form
Dim FormName As String = "MyProj."
 
FormName += Staff.MainFormName
frm = System.Activator.CreateInstance(Nothing, FormName).Unwrap()

Open in new window

siacomAsked:
Who is Participating?
 
JackOfPHCommented:
Try this now...

frm = System.Activator.CreateInstance(Nothing, "MyNameSpace." & Staff.MainFormName.trim).Unwrap()

0
 
David L. HansenProgrammer AnalystCommented:
The code would suggest you are trying to call a project instead of a form, but you want to create a windows form, right?
0
 
siacomAuthor Commented:
no I just wanted to show an existing form within the project.

But the form name is saved in a sql table as a string for retrieving so I want to open the existing form by its form name
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
siacomAuthor Commented:
note staff.MainFormName retrives the formname from a class called staff.

During debugging the class retrurns the propper string as it should.
0
 
David L. HansenProgrammer AnalystCommented:
Why not just do a direct comparison on the string and if it equals, say... "myForm" then instanciate the form (ie. Dim myNewForm As New myForm) and then show it.
0
 
siacomAuthor Commented:
The reason for the break down "MyProj." + FormName is because
System.Activator.CreateInstance will not work without the root namespace.

BUT basically I just want to convert a STRING into a FORM OBJECT so that I can open a form. Yoiu would think this is easy :do accomplish )
0
 
David L. HansenProgrammer AnalystCommented:
Why does Activator need to be used?
0
 
siacomAuthor Commented:
It doesn't.. It's what I tried.  If you n-know a good method to convert a string into a form object please let me know :)
0
 
siacomAuthor Commented:
I tryinmg to cut code by not using comparson... if I can simply open the form dreictly then that would be exactly what i'm looking for.

0
 
David L. HansenProgrammer AnalystCommented:
Ok, so you have the correct string coming back from the database.

If myString = "myForm" then
   Dim newForm As New myForm
End If
newForm.Show

0
 
JackOfPHCommented:
You shuold also include in your string the namespace the form is included...

0
 
JackOfPHCommented:
Dim frm As Form
Dim FormName As String = "MyNamespace." ',<---- This shuold be the namespace the form is included... NOT the project name...
 
FormName += Staff.MainFormName
frm = System.Activator.CreateInstance(Nothing, FormName).Unwrap()
0
 
siacomAuthor Commented:
yes it i the name space name still get exactly the same error message
0
 
JackOfPHCommented:
Can you paste the contents of FormName variable here?
0
 
JackOfPHCommented:
It should return something like this...

"MyNamespace.Form1"

Not

"MyNamespace.Project1.Form1"

0
 
siacomAuthor Commented:
ok the sub is in the code area.

Application:

Asssembly Name:
Easy Filer Professional

Root Namespace
Easy_Filer_Professional
 Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        ' define the Tooltip message
        ' Note: Rather than creating multiple variables with diff message
        ' I will use the REPLACE function to change the message
        ' from username to password.
        Dim Toolmsg As String
        Toolmsg = "<table><tr> "
        Toolmsg += "<td><parm><img src='res://RedError-32x32.gif'></parm></td> "
        Toolmsg += "<td><b><parm>User Name not found</parm></b></td> "
        Toolmsg += "</tr></table> "
        Toolmsg += "<parm><hr noshade size=1 style='margin:2' color=Darker></parm>"
        Toolmsg += "<div style='margin:1 12'><parm>"
        Toolmsg += "  Your User Name is usually the same as you network login name.<br>"
        Toolmsg += "However it can differ for Easy Filer Professional."
        Toolmsg += "</parm></div><parm></parm>"
        Toolmsg += "<table><tr><td><parm></parm></td>"
        Toolmsg += "<td><b><parm></parm></b></td></tr></table>"
 
        ' TODO: Replace the folowing section with proper StafID and details.
        If FindStaffUserName(Me.txtUserName.Text) = Nothing Then
            ErrorProvider1.SetError(Me.txtUserName, "User name not found")
            Me.C1SuperTooltip1.Show(Toolmsg, Me.txtUserName)
 
            Exit Sub
        End If
        Application.DoEvents()
 
        Dim frm As Form
        Dim FormName As String = "Easy_Filer_Professional."
 
        If Me.txtPassword.Text = Staff.Password Then
 
            FormName += Staff.MainFormName
            ' set frm as Form object derived from the Formname as to DB
            frm = System.Activator.CreateInstance(Nothing, FormName).Unwrap()
 
            Staff.IsAuthenticated = True
            LoadChildForm(frm, DockStyle.Fill, False)
        Else
            Toolmsg = Nothing
            Toolmsg = "<table><tr> "
            Toolmsg += "<td><parm><img src='res://RedError-32x32.gif'></parm></td> "
            Toolmsg += "<td><b><parm>Incorrect Password</parm></b></td> "
            Toolmsg += "</tr></table> "
            Toolmsg += "<parm><hr noshade size=1 style='margin:2' color=Darker></parm>"
            Toolmsg += "<div style='margin:1 12'><parm>"
            Toolmsg += "Please retype your password..<br>"
            Toolmsg += "If you cannot remember your password, you will have to contact your Systems Administrator"
            Toolmsg += "</parm></div><parm></parm>"
            Toolmsg += "<table><tr><td><parm></parm></td>"
            Toolmsg += "<td><b><parm></parm></b></td></tr></table>"
 
            ErrorProvider1.SetError(Me.txtUserName, "Incorrect password")
            Me.C1SuperTooltip1.Show(Toolmsg, Me.txtUserName)
 
            Exit Sub
        End If
 
 
 
        Debug.Print("***" & Staff.MainFormName & "***")
 
    End Sub
 
 
 
 
 
 
 
 
 
' FUNCTION
 
 
 Function FindStaffUserName(ByVal username As String) As String
        FindStaffUserName = Nothing
 
        ' Construct SQL Statement as string
        Dim SQLstr1 As String = "SELECT * "
        SQLstr1 += "FROM  Staff "
        SQLstr1 += "WHERE (username = N'" & username & "')"
 
        ' Declare all valid dataset variables
        Dim ds1 As New Data.DataSet
        Dim cn1 As New SqlClient.SqlConnection(My.Settings.SQLConnectionString)
        Dim da1 As New SqlClient.SqlDataAdapter(SQLstr1, cn1)
        Dim dr1 As DataRow
 
 
        da1.Fill(ds1)
        If ds1.Tables(0).Rows.Count > 0 Then
            dr1 = ds1.Tables(0).Rows(0)
            FindStaffUserName = dr1("username")
 
            ' Set the Class Staff vsriables.
            Staff.ID = dr1("StaffID")
            Staff.LoginName = dr1("username")
            Staff.FirstName = dr1("Fname")
            Staff.LastName = dr1("Lname")
            Staff.SecurityLevel = dr1("AccessLevel")
            Staff.DepartmentID = IIf(IsDBNull(dr1("DepartmentID")), 0, dr1("DepartmentID"))
            Staff.Password = dr1("password")
            Staff.MainFormName = dr1("MainModule")
        Else
            FindStaffUserName = Nothing
        End If
 
        ' ==============================
        ' Retrieve GRoup Name
 
        ' Construct SQL Statement as string
        SQLstr1 = Nothing
        SQLstr1 = "SELECT * "
        SQLstr1 += "FROM  Departments "
        SQLstr1 += "WHERE (DepartmentID = " & Staff.DepartmentID & ")"
 
        ' Declare all valid dataset variables
        Dim ds2 As New Data.DataSet
        Dim cn2 As New SqlClient.SqlConnection(My.Settings.SQLConnectionString)
        Dim da2 As New SqlClient.SqlDataAdapter(SQLstr1, cn2)
        Dim dr2 As DataRow
 
        ' IF username was not found in database then skip
        ' Department search and return nothing.
        If FindStaffUserName = Nothing Then GoTo SkipDepartment
 
 
        Try
            da2.Fill(ds2)
            If ds2.Tables(0).Rows.Count > 0 Then
                dr2 = ds2.Tables(0).Rows(0)
                Staff.GroupName = dr2("Department")
            End If
        Catch ex As Exception
 
        End Try
 
 
SkipDepartment:
        cn1.Close()
        cn2.Close()
        da1 = Nothing
        da2 = Nothing
        ds1 = Nothing
        ds2 = Nothing
 
        Return FindStaffUserName
 
    End Function
 
 
 
 
 
'DEclared CLASS
    Public Class Staff
        Public Shared ID As Integer = 0                     ' Relates to the SQL identifier.
        Public Shared LoginName As String = Nothing         ' Retireved from Database
        Public Shared FirstName As String = Nothing         ' Retrieved from database
        Public Shared LastName As String = Nothing          ' Retirved from Database
        Public Shared IsAuthenticated As Boolean = False    ' Determined by code within the login form.
        Public Shared SecurityLevel As Integer = 0          ' Retrieved from database
        Public Shared DepartmentID As Integer = 0           ' Retrieved from database
        Public Shared GroupName As String = 0               ' Retrieved from database
        Public Shared Password As String = Nothing          ' Retrieved from database
        Public Shared MainFormName As String = Nothing      ' Retrieved from database
    End Class

Open in new window

0
 
JackOfPHCommented:
Does the form is in the other project?
0
 
siacomAuthor Commented:
no same project....
0
 
JackOfPHCommented:
Try Triming the Staf.MainFormName, it might have unnecessary spaces at the end since it is from the database...

FormName += Staff.MainFormName.trim
0
 
JackOfPHCommented:
Okey try this...

frm = System.Activator.CreateInstance(Nothing,"Easy_Filer_Professional.MainDBPiForm").Unwrap()

If this run successfully, it means that there is a problem in the FormName variable...

If this does not run check the case of the form name... it should be it proper casing.

MyForm is different from myForm...
0
 
JackOfPHCommented:
>>Could not load type 'MyProj.MainDBPiForm' from assembly 'My Project, Version=1.1.4.25, Culture=neutral, PublicKeyToken=null'.

I notice in the error that you where including the ProjectName which is wrong...

As I said earlier it should be the namespace...
0
 
siacomAuthor Commented:
OK I double click on application ->>> goto the Root namespace textbox and copy the namespace which is:

Easy_Filer_Professional


are you saying that this is wrong ? and if so then where else am i getting the namesapce from ?

0
 
JackOfPHCommented:
That is right...

Did you try this?
frm = System.Activator.CreateInstance(Nothing,"Easy_Filer_Professional.MainDBPiForm").Unwrap()

0
 
JackOfPHCommented:
Does my last post run?
0
 
siacomAuthor Commented:
just tried: this error occured:

Could not load type 'Easy_Filer_Professional.MainDBPiForm' from assembly 'Easy Filer Professional, Version=1.1.4.25, Culture=neutral, PublicKeyToken=null'.

by the way, the caps are exactly the same, I usually use copy and paste to elevuate typos with variables.



0
 
JackOfPHCommented:
Does the form name is in proper case?
0
 
siacomAuthor Commented:
could i be missing something like imports ?
0
 
siacomAuthor Commented:
the form name is Exactly the same caps as the variable value
0
 
JackOfPHCommented:
Honestly, I am now running out of idea...
:(
0
 
siacomAuthor Commented:
lol .. so am i

I just dont know why., I will isolate this function in a tiny project and have a totally different namespace from project name and see the outcome.

I will post back the results tomorrow (time to go home)

In the meantime I have opted for a if/else evaluation because select case doesn't want to play nice either.

thanks for your help though.



0
 
David L. HansenProgrammer AnalystCommented:
To get the correct namespace look in the "My Project" settings window (double click on "My Project" in Solution Explorer).  Then click on the "Application" tab; the second textbox over is the namespace.

Also, if you can see the form, open the code.  Now look at the top where the class is declared (like "Public Class myForm").  If you can see the name of the class you most certainly can instanciate it.

Just as a test try only this :
"Dim myNewForm As New myForm"
Use this in another module or class outside of the target form's code.  If you get errors with that then there is something seriously wrong.
0
 
siacomAuthor Commented:
actually that is exactly what i did yesterday as a final solution, although I would prefer the other way :)

my code is in the code section below:


            ElseIf Staff.MainFormName = "MainDBPiForm" Then
                frm = New MainDbPiForm
                GoTo LoginFormValidated
                ' Second trap in case value is totally different.


this works fine.

Dim frm As Form
 
            If Staff.MainFormName = Nothing Then
                MsgBox("error", MsgBoxStyle.Critical)
                Exit Sub
 
                ' PI Form
            ElseIf Staff.MainFormName = "MainDBPiForm" Then
                frm = New MainDbPiForm
                GoTo LoginFormValidated
                ' Second trap in case value is totally different.
            Else
                MsgBox("ERROR, cannot evaluate argument", MsgBoxStyle.Critical)
                Exit Sub
            End If
 
 
 
LoginFormValidated:
        Staff.IsAuthenticated = True
 
        LoadChildForm(frm, DockStyle.Fill, False)
 
 
 
 
    Public Sub LoadChildForm(ByVal FormName As Form, _
                             ByVal DockingStyle As DockStyle, _
                             ByVal CentreForm As Boolean)
 
        MainForm.IsMdiContainer = True
 
        FormName.MdiParent = MainForm
        FormName.Dock = DockingStyle
        FormName.Show()
        FormName.Focus()
        If CentreForm Then
            FormName.StartPosition = FormStartPosition.CenterParent
        End If
 
        ThisApp.FormFocused = FormName.Text
    End Sub

Open in new window

0
 
David L. HansenProgrammer AnalystCommented:
Great! So it works????
0
 
JackOfPHCommented:
One more thing... I just crossed this a minute ago...

Did you enable the clickonce security setting? If so you have to included the reflectionPermission in your project....

To do so... go to the project properties, then click security then If the Enable Clickonce security Setting is checked then include the Reflection permission in the grid...

I hope this time it will solve your original question...

Jack
0
 
siacomAuthor Commented:
I've unticked the ClickOnce (didn't even know it was enabled)  and get this error:

         frm = System.Activator.CreateInstance(Nothing, _
                                   Type.GetType("MyNameSpace." + Staff.MainFormName)).Unwrap()

Value cannot be null. Parameter name: type

Whenh I tick Enable ClickOnce and change it to partial then calculate it claims that this application cannot run in partial and needs Full Trust if I leave it at full trust then I cannot change any settings like ReflectionPermission as it is greyed out...

I'm experimenting with this at the moment though


0
 
JackOfPHCommented:
frm = System.Activator.CreateInstance(GetType(frm), _
                                   Type.GetType("MyNameSpace." & Staff.MainFormName)).Unwrap()
0
 
siacomAuthor Commented:
this doesn't work because it claims I haven;t defined it.

Dim frm As Form

frm = System.Activator.CreateInstance(GetType(frm), _
                                   Type.GetType("MyNameSpace." & Staff.MainFormName)).Unwrap()


0
 
JackOfPHCommented:
okey try to replace it with this one

GetType(System.Windows.Forms.Form)

frm = System.Activator.CreateInstance(GetType(System.Windows.Forms.Form), _
                                   Type.GetType("MyNameSpace." & Staff.MainFormName)).Unwrap()
0
 
siacomAuthor Commented:
I start a New Project with absolutely nothing but the code below:

There are 2 forms.

Form1
Form2

This error still occurs:
Value cannot be null. Parameter name: type



Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
        Dim frm As Form
        Dim frmStr As String = "Form2"
 
        frm = System.Activator.CreateInstance(Nothing, _
                      Type.GetType("InstanciateThis.Form2")).Unwrap()
 
        frm.Show()
 
    End Sub

Open in new window

error.jpg
0
 
siacomAuthor Commented:
sorry wrong file.
error.jpg
0
 
JackOfPHCommented:
Dim frm As Form
        Dim frmStr As String = "Form2"
 
        frm = System.Activator.CreateInstance(Nothing, _
                      "InstanciateThis.Form2").Unwrap()
 
        frm.Show()
0
 
JackOfPHCommented:
TRy the above code...

0
 
JackOfPHCommented:
frm = System.Activator.CreateInstance(Nothing, "MyNameSpace." + Staff.MainFormName).Unwrap()


0
 
JackOfPHCommented:
Does it work?
0
 
siacomAuthor Commented:
no
0
 
siacomAuthor Commented:
sprru about that i did not read your message above.

Yes THIs WORKS.
        Dim frm As Form
        Dim frmStr As String = "Form2"

        frm = System.Activator.CreateInstance(Nothing, _
                      "InstanciateThis.Form2").Unwrap()

        frm.Show()

0
 
JackOfPHCommented:
If this is in the module then:

Dim frm As Form
        Dim frmStr As String = "Form2"
 
        frm = System.Activator.CreateInstance(GetType("System.Windows.Forms.Form", _
                      "InstanciateThis.Form2").Unwrap()
 
        Application.Run(frm)
0
 
siacomAuthor Commented:
when I go back to the other project this error occurs:

Could not load type 'MyRootName.form1' from assembly 'My Assembky Name, Version=1.1.4.25, Culture=neutral, PublicKeyToken=null'.
0
 
JackOfPHCommented:
but before doing so, remember to unticked the Enable clickonce Security Setting...
0
 
siacomAuthor Commented:
What the ...
I tried that the very first time and it didn't work.

ok anyway that did work for both projects. thank you !!!

you shuild get a couple of thousand points for this one :)



0
 
siacomAuthor Commented:
Thanks for your help.
This did work with Full trust security enabled.
0
 
JackOfPHCommented:
Finally, I think the cause of the problem is the clickonce security setting...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.