Displaying the VB.NET Form Dynamically from a String Variable

By: Ahmar
DOWNLOAD AS PDF

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!

latest news

01

5 signs your company needs an ERP

An ERP system captures information from all departments, and it may be time for you to implement it within your organization. Here are 5 signs that make it clear your business will benefit from an ERP system.

02

7 Benefits of an ERP System For Your Business

ERPs manage the core processes of an organization – from HR to sales to finance – and house all the data. Many ERPs also offer increased visibility, analytics, and efficiency across the company. Let’s explore some of the benefits of running your business on an ERP system

03

8 Benefits to Adopting DevOps into your Organization

Under DevOps, a “product-first” approach, companies align development projects with the business goals of operations so teams can jointly build, test, release, and maintain new digital applications more frequently and more efficiently. What benefits does DevOps offer?

Copyright© 2018 alligatortek. All rights reserved.