Multi-Form Applications

Advanced 25 min read Lesson 6 of 7

Real applications rarely fit on one form. This lesson covers navigating between forms and passing data cleanly.

Opening a second form (non-modal)

private void btnOpenReports_Click(object sender, EventArgs e)
{
    var reportsForm = new ReportsForm();
    reportsForm.Show();   // Show() = non-modal, user can switch between windows
}

Opening a form modally and getting data back

private void btnAddStudent_Click(object sender, EventArgs e)
{
    using var addForm = new AddStudentForm();

    if (addForm.ShowDialog(this) == DialogResult.OK)
    {
        // addForm exposes public properties set right before closing
        InsertStudent(addForm.FirstName, addForm.LastName, addForm.Email);
        LoadStudents();
    }
}

Exposing data from a child form

public partial class AddStudentForm : Form
{
    public string FirstName => txtFirstName.Text;
    public string LastName => txtLastName.Text;
    public string Email => txtEmail.Text;

    public AddStudentForm()
    {
        InitializeComponent();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(txtFirstName.Text))
        {
            MessageBox.Show("First name is required.");
            return;
        }

        DialogResult = DialogResult.OK;  // closes the form automatically
    }
}

Choosing a "main form" pattern (MDI)

For apps with many child windows docked inside one parent (like an old Office app), set IsMdiContainer = true on the main form and MdiParent = this; before showing a child form. Most modern apps skip MDI in favor of a single main form with panels/tabs, which is simpler to maintain.

Sharing a connection string across forms

public static class AppConfig
{
    public const string ConnectionString =
        "Server=localhost\\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;TrustServerCertificate=True;";
}

// Used anywhere:
using var connection = new SqlConnection(AppConfig.ConnectionString);
Key Takeaway

Multi-form apps use Show() for non-modal and ShowDialog() for modal forms. Use public properties or a shared config class to pass data between forms.

Test Your Knowledge - Take Quiz