[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Open form based on TreeView Selection visual studio

Posted on 2016-07-26
5
Medium Priority
?
130 Views
Last Modified: 2016-07-26
Hi all.

I'm working on a vb.net project in Visual Studio. The "Menu" form has a TreeView control. When the end user clicks a node then I want to open the form that corresponds to the selected node. All of the forms are within the same project. I'm basically trying to make the treeview work as a menu or switchboard.

The problem is that there could be 50 to 60 nodes and I'd like to avoid having to do 50-60 case statements or if else statements to open the forms.

So I was working on the code below but I'm getting the following error because I can't cast from a string to a form, so can someone provide any suggestions as to how I can get this to work?

Thank you in advance!

ERROR: Unable to cast object of type 'System.String' to type 'System.Windows.Forms.Form'.

Code:
Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
Dim con As New SqlConnection
        Dim cmd As New SqlCommand
        Dim frm As New Form

        con.ConnectionString = "Data Source=myServer;Initial Catalog=myDB;Integrated Security=True"

        con.Open()

        cmd.Connection = con

If e.Node.Text = "PM App" Then
            Exit Sub

        Else
            cmd.CommandText = "SELECT FormName FROM Menu WHERE Application = @Form"
            cmd.Parameters.AddWithValue("@Form", TreeView1.SelectedNode.Text)
           
            frm = cmd.ExecuteScalar()
         
            frm.Show()
            con.Close()

        End If

End Sub

Open in new window

0
Comment
Question by:printmedia
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 2000 total points
ID: 41729819
You need to use something like this:
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim f As Form = GetFormByName("Form2")
        f.Show()
    End Sub

    Private Function GetFormByName(ByVal pFormName As String) As Form
        'first try: in case the full namespace has been provided (as it should ;-) )
        Dim T As Type = Type.GetType(pFormName, False)
        'if not found prepend default namespace
        If T Is Nothing Then
            Dim strFullname As String = Application.ProductName & "." & pFormName
            T = Type.GetType(strFullname, True, True)
        End If
        Return CType(Activator.CreateInstance(T), Form)
    End Function

Open in new window

0
 

Author Comment

by:printmedia
ID: 41729879
Thanks Eric that worked.

I'd like to understand the code, so I have a couple of questions:

(1) What does the Type.GetType(pFormName, False) do exactly because testing the code out, it actually goes into the If statement . Is it checking to see if pFormName is of any known object type (i.e. String, Form, ListBox etc.). If it can't find it then the "False" part means do not throw an exception and just continue on to the If statement?

(2) In the line T = Type.GetType(strFullname, True, True), is the first "True" to throw an exception and the second to do a case-sensitive search?

(3) In the last line, CType is converting T to a new Form instance?
0
 
LVL 34

Expert Comment

by:it_saige
ID: 41729931
Type.GetType(String, Boolean), attempts to Get the Type specified by the Name, performing a case-sensitive search and specifying whether to throw and exception if the type is not found.

Type.GetType(String, Boolean, Boolean), does the exact same thing as the previous with the difference being that you can control the search case-sensitivity.

You have noticed that Eric switches from throwing no exception to throwing an exception.

As for the last line, you have to create an instance of the type, Eric has specified to create an instance using the empty constructor.  This is the same thing as perfoming either of the following:
Dim f1 As Form = New Form()
'' Or
Dim f1 As New Form()

Open in new window


-saige-
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41729934
you should first have a look at https://msdn.microsoft.com/en-us/library/c5cf8k43(v=vs.110).aspx

Type.GetType tries to create a type form the name specified in the string. The False value is just to prevent an exception to be thrown because we are checking on the following if the Type is null (meaning not found).

Because forms belongs to namespaces in .Net, we are trying to add the current namespace to the form name in also use the 3rd argument to specify to do a case-insensitive operation.

The last line cast the returned type to a form.
0
 

Author Closing Comment

by:printmedia
ID: 41729944
Thank you!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

656 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question