Button access from other form

amitairoa

Newcomer
Joined
Jul 16, 2008
Messages
21
Hi!
I have a program in C# which has two forms.
I would like to put a button on Form1, and then the user can change
the button's settings On Form2.
The problem is- how do I access the button that's on Form1- from Form2?
On Form1- the code is:
Code:
Button Button1 = new Button();
On Form2- for instance- the user can choose the buttons text- and write it in a textbox on that form. When the user clicks ok- I want to implement the text written in the textbox on Form2- to button1- on Form1.
How do I do this when the button is on the other form?
Please help.
Thanks!
 
You have a couple of options -- if you want the changes to presist through sessions of your application you'll want to save to a text/xml/database file when the users changes settings on Form2; in order to load those settings you could use a FileSystem watcher and look for changes to your config file.

Another approach would be to add an overloaded constructor for Form2 that accepts a reference of Form1 which contains your button [you would need to declare the button as Public] then, you have full access to all properties of Form1 [including the button] from the context of Form2

Form1 Code
C#:
....
public Button button1 = new Button(...);
....
void LoadUpForm2()
{
    Form2 f = new Form2(this);
    f.Show();
}

Form2 Code
C#:
Form1 theMainForm
void Form2(Form1 mainForm)
{
    theMainForm = mainForm;
}

protected void textBox1_TextChanged(...)
{
    theMainForm.button1.Text = textBox1.Text;
}

I didn't run that through the compiler, but it should get you started.
 
Back
Top