Re: showdialog and 'Cannot access a disposed object'

chris Burgess <[email protected]> Tue, 8 Jan 2008 14:39:40 -0500
Newsgroups gmane.comp.windows.devel.dotnet.winforms
Message-ID <[email protected]>
How do I pass the report type (derived from BaseForm) to the CreateForm class?

To create the form, I have this:
Public Function CreateForm(Of ItemType As {BaseForm, New})() As ItemType
        Return New ItemType
End Function

I created two forms derived from BaseForm called ChildForm1, ChildForm2

if I do this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
        Dim f As BaseForm
        f = CreateForm(Of ChildForm1)()
        f.ShowDialog()
    End Sub

It works fine.

What I'd like to do is something like this:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
        Dim f As BaseForm
        Dim reports As New List(Of BaseForm)
        reports.Add(childform1)
        reports.Add(ChildForm2)

        f = CreateForm(Of reports.item(0))()

    ' Or
     '  Dim r As BaseForm = reports.Item(0)
     '  f = CreateForm(Of r)()

       f.ShowDialog()
    End Sub

Or something like that. I don't understand what I need to pass to the
CreateForm function.









On Jan 7, 2008 8:49 AM, Mike Andrews <[email protected]> wrote:
> If you need to be able to specify a type for the "form" and then create it
> if it's not been created yet or show it if it has, you can use generics to
> your advantage here.
>
> Create a method called CreateForm(Of T) or some such name like this:
>
>    Public Class BaseForm
>        Inherits System.Windows.Forms.Form
>    End Class
>    Private ShownForms As New Dictionary(Of String, BaseForm)
>    Public Function CreateForm(Of ItemType As {BaseForm, New})() As ItemType
>        Dim form As ItemType
>        Dim key As String = GetType(ItemType).Name
>        If Not ShownForms.ContainsKey(key) Then
>            form = New ItemType()
>            'Set other form parameters here
>            ShownForms.Add(key, form)
>        Else
>            form = CType(ShownForms(key), ItemType)
>        End If
>        Return form
>    End Function
>
>