0

I have a Form, name it MainView. In MainView i have a usercontrol:enter image description here

I do something in the usercontrol, then click to "OK". Due to the OK button i would like to hide this usercontrol and open another. But i can't access another usercontrol from the first.

  • 1
    You can let the surrounding form catch the buttons click event or even better throw a new usercontrol specific event from the buttons eventhandler on the usercontrol that then is handled by the form. Then the form can call something on the other usercontrol. Don't try to make usercontrols talk to each other directly. That's normally a dead end. – Ralf Jan 09 '23 at 08:30
  • 1
    [Pass event of child control to the parent form](https://stackoverflow.com/a/36130796/3110834) – Reza Aghaei Jan 09 '23 at 10:07

1 Answers1

0

One simple way to create the appearance of "bringing to front a user control" would be having each user control Hide() itself when the [OK] button is clicked. Then the main form can modify the visibility of the "other" form based on the non-visibility of the first:

screenshot


Main View

Toggle the visibility of user controls when the OK button is clicked.

public partial class MainView : Form
{
    public MainView()
    {
        InitializeComponent();
        userControlB.Visible= false;
        userControlA.VisibleChanged += (sender, e) =>
        {
            if(!userControlA.Visible)
            {
                userControlB.Visible = true;
            }
        };
        userControlB.VisibleChanged += (sender, e) =>
        {
            if (!userControlB.Visible)
            {
                userControlA.Visible = true;
            }
        };
    }
}

UserControl A

public partial class UserControlA : UserControl
{
    public UserControlA()
    {
        InitializeComponent();
        buttonOK.Click += (sender, e) =>
        {
            Hide();
        };
    }
}

UserControl B

public partial class UserControlB : UserControl
{
    public UserControlB()
    {
        InitializeComponent();
        buttonOK.Click += (sender, e) =>
        {
            Hide();
        };
    }
}
IVSoftware
  • 5,732
  • 2
  • 12
  • 23