views:

64

answers:

2

I am attempting to show a specific form using a treeview control, the nodes of which have their tag value set to an instance of the Form I need to show. The code I have in the DoubleClick event works great for the first time I show a form, but after that I get an object disposed exception. As you can see, I tried handling it by resetting the tag, but that didn't work. Is there any way I can show the form more than once without going through a switch statement anytime the exception comes up and resetting the tag to the right type of form? I'd like something nicer looking like the way I show the form.

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim fm2 As New Form2()
        Dim fm3 As New Form3()
        TreeView1.Nodes(0).Tag = fm2
        TreeView1.Nodes(1).Tag = fm3
    End Sub

    Private Sub TreeView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.DoubleClick
        Try
            CType(TreeView1.SelectedNode.Tag, Form).Show()
        Catch odex As ObjectDisposedException
            TreeView1.SelectedNode.Tag = New Form()
            TreeView1_DoubleClick(sender, e)
        Catch nrex As NullReferenceException
            'No node selected, do nothing.  
        End Try
    End Sub
End Class
+1  A: 

The form gets disposed when it is closed by the user. One option is to handle Closing event of the form ans just hide it instead of closing.

Giorgi
+1  A: 

Your problem here is if the user closes the form, the object will have been disposed.

There are a few ways you can handle this, some more elegant than the other.

  1. Add a handler for FormX_Closed() at this time you can reset the tag reference
  2. You could switch to a "Show dialog" process and then reset before your DoubleClick() method ends

It really depends on what these forms are doing. Typically i would see your DoubleClick method doing a lookup then creating the instance, simply because if you create instances you are using memory that might not be needed, but that is something that might be necessary considering your application.

Lookup Example

As requested in the comments, if I were to do this a different way, I would use an enumeration value, or even a simple integer "key" value for the tag. Then I would create something like the following to show it.

Select Case myTag
    Case 1
        Dim formInstance As New Form1()
        formInstance.Show()
    Case Else
        Dim formInstance As New Form2()
        formInstance.Show()
End Select

Basically centralize it and launch the form on demand, you could switch this out for another design pattern if you wanted more control or had a lot of different form types.

Mitchel Sellers
How would you do the lookup to create the instance?
Caleb Thompson
Added example, "myTag" is your current tag value
Mitchel Sellers