Home > Blockchain >  Use method from class in form
Use method from class in form

Time:09-22

Plese help me i have class in my project named Visibility.cs and i wanna use method named HospodaVisible() in Form1 but it doesnt work :/ it isnt showing usercontrol

here is code of class and form1:

    public static class Visibility
    {
        static Form1 f = new Form1();
        public static void HospodaVisible()
        {
            f.hospoda1.Visible = true;
            f.arena1.Visible = false;
            f.podzemi1.Visible = false;
        }
        public static void ArenaVisible()
        {
            f.hospoda1.Visible = false;
            f.arena1.Visible = true;
            f.podzemi1.Visible = false;
        }
        public static void PodzemiVisible()
        {
            f.hospoda1.Visible = false;
            f.arena1.Visible = false;
            f.podzemi1.Visible = true;
        }
    }
    
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            hospoda1.Visible = false;
            arena1.Visible = false;
            podzemi1.Visible = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Visibility.HospodaVisible();
        }
    }

CodePudding user response:

See if this works for you:

    public static class Visibility
    {
        public static void HospodaVisible(Form1 f)
        {
            f.hospoda1.Visible = true;
            f.arena1.Visible = false;
            f.podzemi1.Visible = false;
        }
    }
    
    public partial class Form1 : Form
    {
        private void button1_Click(object sender, EventArgs e)
        {
            Visibility.HospodaVisible(this); // passes a reference to the "current" form, i.e. Form1 itself
        }
    }

this is a reference to the current instance of a class inside the class, in other words it's self.

In the code above you passes a reference to the active, current form to a static helper method which accepts a reference to a form (doesn't instantiates one) and makes the necessary changes to it. Basically, it says: "hey helper, do something with this form".

  • Related