Search code examples
c#staticpanel

Displaying a panel in another windows form on button click c#


I'm working on a c# program and I want a panel to appear on a form when a button is clicked in another. So when the add button is clicked on form2 the panel requesting the details for this to be possible will be displayed on form 1.

I currently have a static method set up in form1 which can be accessed from form2 - however due to panel.Show() being non static it won't allow me to use this in the function.

In Form1 I have:

public static void showPanel()
{
   panel.Show()
}

In my second form I have the following:

private void btn_add_Click(object sender, EventArgs e)
{
   form1.showPanel();
   this.Hide();
}

I have tested with just having the static function show a message box which works. Is it possible to do it the way I want or do I need to take a few steps back and try a different technique?


Solution

  • Are we talking about a new instance of the second form if so you can try to instantiate the new form using:

    Form newForm = new YourFormName(potential parameters); newForm.showPanel(); newForm.Show();

    If you want to execute the form on an open form you can give the first form a reference(field with instance) of the second form. Or you can try using: Application.OpenForms. if you give it [1] it'll give you the second open form probably. You can also use .OfType to get the correct form in case your form order isn't always the same.