0
votes

I want to use the controls of a form from a generic class. In VB is very easy but in C# is difficult as I am trying to learn it. So searching I found an ease answer to this and I am coping here


Set the control to public in the designer:

  public System.Windows.Forms.Button button1;

Create a new class and for example rename it to exampleClass

  public class exampleClass
  {
      public static Form1 frm;
      public static void HideButton()
      {
    frm.button1.Visible = false;
      }
  }

Add this after Form1 InitializeComponent:

  exampleClass.frm = this;

Now you can hide the button from anywhere you want:

  exampleClass.HideButton();

My question now is: If we want to make more general and pass the control and the status (true/false) to the class method eg

 exampleClass.HideButton(Control, Status) 

How can we do?

Thanks in advance, Elias

4

4 Answers

2
votes

Well it's straight forward:

public class ExampleClass
{
    public static void HideControl(Control control, bool hide)
    {
        if (control != null) control.Visible = !hide;
    }
}

And you call it like

ExampleClass.HideControl(frm.Button1, true);

But after writing this I wonder, why do you need this? If you have your Button already, why not simply call

frm.Button1.Visible = false;

instead of another static method?

0
votes

Just implement it as you describe: pass the control and the status to the method as parameters. Don't forget to include: using System.Windows.Forms;

public class Class2
{
    public static void HideButton(Control c, bool status)
    {
        c.Visible = status;
    }
}

and use the external class in the WinForm like this:

Class2.HideButton(this.button2, false);

PS. I misread in the first version. You wanted to have a static method. Changed it

0
votes

Why not simply:

public static void HideControl(Control control, bool visible)
{
    control.Visible = visible;
}
0
votes

In this example you have a form called Form1.cs and a class called exampleClass:

In exampleClass (Note: the name of my Form Class = 'Form1'):

Form1 ui = new Form1();
ui.button1.Visible = false;

In (FormName).Designer.cs so in my case Form1.designer.cs change the appropriate control from 'private' to 'public':

public System.Windows.Forms.Button button1;