In this blog, I will talk about how to open a form dynamically in Visual Basic .NET if the form name is provided in a string variable or fetched from the Database.
Let’s look at the code:
Let’s put a button on the form and add the following method to it:
Public Sub showFormDynamically(frmForm As String) Dim obj As Object = Activator.CreateInstance(Type.GetType("MYASSEMBLYNAME." + frmForm)) obj.ShowDialog() End Sub
This method is the crux of this exercise – It takes a form name in a string variable, passes that string and the assembly name to Activator.CreateInstance, and displays that form on the screen.
Activator.CreateInstance creates an instance of the specified type using the type’s constructor. In this case the type is Windows Forms.
The next step is to call this method. In this example, we have a form – “frmFormToOpen” – that I like to open when a button on another form – “frmForm1” – is clicked. Here is the content of the event on the “frmForm1”;
Dim vForm As String vForm = "frmFormToOpen" AppUtilities.showFormDynamically(vForm)
The third line of the above code will show a form “frmFormToOpen”. For this example I hardcoded the form name, but you can pass the form name retrieved from the database.
Don’t forget to share your feedback. Happy coding!