Click to See Complete Forum and Search --> : Beginner... access Form1 method from another class


valkyr
September 13th, 2009, 02:20 PM
I've spent a ridiculous amount of time trying to find an answer to what seems like it should be so easy with no success...

How do I reference Form1 in the below, without using "((Form1)Form1.ActiveForm)"?

That works, but obviously crashes the app if you click off it while something that's using it is working.


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

private void button1_Click(object sender, EventArgs e)
{
changetext cg1 = new changetext();
cg1.textbox1();
}

public void change_textbox_text(string input)
{
this.textBox1.Text = (input);
}
}

class changetext
{
public void textbox1()
{
((Form1)Form1.ActiveForm).change_textbox_text("OK");
}
}
}

BigEd781
September 13th, 2009, 03:05 PM
So, you should not be doing this at all. There is no god reason to access your form class from another class. This is something that beginners often want to do (myself included), but it is a bad idea. Code like this is tightly coupled. Your 'changetext' class now depends on the implementation of your form class and also shares the responsibility of updating the UI. This kind of code is hard to maintain, fragile, and can be hard to debug.

Instead, just had your class raise an event or return data from a method. Your form class can use your class and your form will stil be responsible for updating the UI.

To answer your actual question, you could simply pass in a reference to a Form1 object in your class' constructor as a parameter to the method.


class changetext
{
public void textbox1(Form1 form)
{
form.change_textbox_text("OK");
}
}


Again though, this is bad code and you should not use it.

rliq
September 15th, 2009, 08:43 PM
Following on from what Ed said... As a step in the right direction, without altering your code too much:

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

private void button1_Click(object sender, EventArgs e)
{
ChangeText cg1 = new ChangeText();
textBox1.Text = cg1.textbox1();
}
}

class ChangeText
{
public String textbox1()
{
return "OK";
}
}