Home > Software engineering >  Changing properties of a button via method from another class
Changing properties of a button via method from another class

Time:10-20

Maybe you can help me with my problem.

My Class "Form1" calls the method setButtons();

but setButtons() ist not at Class "Form1", its in Class "Class1".

setButtons() in "Class1" does not recognice Button1 from Form1.

How do I let it know that Button1 exists in Form1 and I want the method to work on the Button1 from "Form1"? Class1 has already a using directory to Form1 and Form1 has one to Class1.

//this does not work
public static void setbuttons()
{
    Form1.Button1.Location = new Point(40, 40);
}

CodePudding user response:

I found out that if you declare a control public in the designer file like so

public Button button1;

Then you can access it from another class on the condition that you get the form object, for example as a extension

static class AnotherClass
{
    public static void setButtons(this Form1 form)
    {
        form.button1.Text = "Hello";
    }
}

A better way to change the properties of a button, in terms of design and code management, would be to make a method in your form that does it.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        ...
    }

    public void ChangeButtonTextMethod(string text)
    {
        button1.Text = text;
    }
}

CodePudding user response:

Consider using an event where the method in Class1 passes a Point to the calling form which listens for the event, in this case SetButtons.

public class Class1
{
    public delegate void OnSetLocation(Point point);
    public static event OnSetLocation SetButtonLocation;

    public static void SetButtons()
    {
        SetButtonLocation!(new Point(40, 40));
    }
}

In the form subscribe to SetButtonLocation, invoke the method SetButtons which passes a Point to the caller in Form1 and in turn sets the button Location.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Class1.SetButtonLocation  = OnSetButtonLocation;
        Class1.SetButtons();
        Class1.SetButtonLocation -= OnSetButtonLocation;
    }

    private void OnSetButtonLocation(Point point)
    {
        button1.Location = point;
    }
}

Using this approach is better than changing the modifers of form to public as mentioned already.

  • Related