Click here to Skip to main content
15,915,328 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi, How can I access my button _which is on my form_in my class?
Posted
Comments
[no name] 24-Nov-11 10:19am    
What class? Please provide full details when asking a question
LanFanNinja 24-Nov-11 10:42am    
Check my solution

1 solution

Well there are a lot of ways to do this but maybe this will give you an idea of something you could do.

C#
public partial class Form1 : Form
{
    public Button MyButton
    {
        get { return button1; }
        set { button1 = value; }
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        MyClass mc = new MyClass(this);
    }
}


C#
class MyClass
{
    Form1 mainForm;

    public MyClass(Form1 form1)
    {
        mainForm = form1;

        //access your button through mainForm
        mainForm.MyButton.Text = "MyText";
    }
}


You could also just pass your Button to your class instead of passing a reference to your form like so
C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        MyClass mc = new MyClass(button1);
    }
}


C#
class MyClass
{
    Button myButton;

    public MyClass(Button myButton)
    {
        this.myButton = myButton;

        //access your button
        myButton.Text = "MyText";
    }
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900