VB.NET•Display the Appropriate Type

Listing 2. Creating a dynamic menu is only half the story. When the user clicks on a dynamic menu option, you must present the appropriate display for this type. Instantiating the type is easy through Reflection. The common base class guarantees that specific methods are available, and you can use one of these methods to display the type.

Private Sub mnuDynamicItem_Click(ByVal sender _
	As Object, ByVal e As System.EventArgs)
	onDynamicItem(sender, e)
End Sub
Protected Overridable Sub onDynamicItem(ByVal _
	sender As Object, ByVal e As System.EventArgs)
	Dim type As System.Type
	Dim frm As BaseEditForm
	Dim obj As System.Object
	If TypeOf sender Is MenuItemWithType Then
		type = CType(sender, _
		obj = Activator.CreateInstance(type)
		If Not obj Is Nothing AndAlso TypeOf obj _
			Is BaseEditForm Then
			frm = CType(obj, BaseEditForm)
			AddHandler frm.StateChanged, _
				AddressOf SetState
		End If
	End If
End Sub