In this tutorial, we will delve into the world of dynamic form navigation in C#. Specifically, we will learn how to display different forms within a single panel on the home form. This is a powerful technique that can greatly enhance the user experience of your Windows Forms applications.
What is Dynamic Form Navigation?
Dynamic form navigation is a method of managing multiple forms in a single application. Instead of opening each form in a new window, we can display them within a panel on the home form. This makes for a smoother, more integrated user experience.
Our Application
Our application consists of two forms: the Home form and the Employee form. The goal is to display the Employee form within a panel on the Home form when a button is clicked.
The Code
The core of our dynamic form navigation lies in two pieces of code: the formmenu method and the btEmployee_Click event.
The formmenu Method
The formmenu method is responsible for managing the forms within our panel, named pannelConnector. Here’s what it looks like:
private void formmenu(object allform)
{
if (this.pannelConnector.Controls.Count > 0)
this.pannelConnector.Controls.RemoveAt(0);
Form fs = allform as Form;
fs.TopLevel = false;
fs.Dock = DockStyle.Fill;
fs.FormBorderStyle = FormBorderStyle.None;
this.pannelConnector.Controls.Add(fs);
this.pannelConnector.Tag = fs;
fs.Show();
}
This method first checks if there are any controls in our panel. If there are, it removes the first one. Then, it sets some properties for our form, adds it to the panel, and finally shows the form.The btEmployee_Click Event
private void btEmployee_Click(object sender, EventArgs e)
{
formmenu(new Employee());
}