n00bAppDev
n00bAppDev

Reputation: 630

Multiple Pages within one Form? C#

I haven't done this for a while so am not quite sure how to do what I need, but I am sure it is pretty simple.

Basically, I have a form with a navigation pane. I want to make it so when a user clicks a button on that pane, say 'Home' it changes the content on the form, but doesn't actually switch to another form, if you get me?

As in, I would like the navigation pane to stay as it is the entire time and I only want the content of the form to change. It is almost like the 'TabControl' tool in Visual Studio's 'Toolbox' although instead of the tabs being directly above the content, I want them to be buttons displayed in a side pane. See the image below for a better understanding. Thanks!

(Side pane, and header stays the same regardless on what button is pressed, but the content changes.)

Form

Upvotes: 7

Views: 22388

Answers (3)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

I'd implement this using UserControls. One UserControl is shown when a button is clicked. I'd create an interface (for example IView) that would be implemented by each UserControl that declares common functionality, like for example a method to check whether you can switch from one to another (like a form's OnClosing event) like this:

public interface IView
{
    bool CanClose();
}

public UserControl View1: IView
{
    public bool CanClose()
    {
       ...
    }
}

public UserControl View2: IView
{
    public bool CanClose()
    {
       ...
    }
}

Then, switching views is quite easy:

private bool CanCurrentViewClose()
{
    if (groupBox1.Controls.Count == 0)
        return true;

    IView v = groupBox1.Controls[0] as IView;
    return v.CanClose();
}

private void SwitchView(IView newView)
{
    if (groupBox1.Controls.Count > 0)
    {
        UserControl oldView = groupBox1.Controls[0] as UserControl;
        groupBox1.Controls.Remove(oldView);
        oldView.Dispose();
    }
    groupBox1.Controls.Add(newView);
    newView.Dock = Dock.Fill;
}

In a button you could do this:

private void btnHome_Click(object sender, EventArgs e)
{
    if (CanCurrentViewClose())
    {
        ViewHome v = new ViewHome();
        // Further initialization of v here

        SwitchView(v);
    }
    else
    {
        MessageBox.Show("Current View can not close!");
    }
}

I've successfully used this approach on many occasions.

Upvotes: 8

sh_kamalh
sh_kamalh

Reputation: 3901

You can simply use a TabControl which has as many TabPages as you want. For the TabControl you can set the Alignment property to Left

Upvotes: 0

Mastenka
Mastenka

Reputation: 345

Simplest way is to place multiple Panels as content holders, implement content manager which keeps references to Panels and with it show/hide desired panel.

Simple, but for smaller apps it will work

Upvotes: 7

Related Questions