|
-
September 13th, 2009, 02:20 PM
#1
Beginner... access Form1 method from another class
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.
Code:
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");
}
}
}
-
September 13th, 2009, 03:05 PM
#2
Re: Beginner... access Form1 method from another class
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.
Code:
class changetext
{
public void textbox1(Form1 form)
{
form.change_textbox_text("OK");
}
}
Again though, this is bad code and you should not use it.
-
September 15th, 2009, 08:43 PM
#3
Re: Beginner... access Form1 method from another class
Following on from what Ed said... As a step in the right direction, without altering your code too much:
Code:
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";
}
}
Rob
-
Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|