Calling a Form component from a child class
What is the best OO practice for accessing a Form component from a child class?
For example in my Form1 class I have an instance of a class MyClass. Form1 has a Label component. I'd like to change this label component from within MyClass.
How can I do this nicely without breaking some OO principles.
Thanks.
bobPosted Oct 19, 2009, 4:00 PM
Serban CosminPosted Oct 19, 2009, 12:12 PM
Kirtan PatelPosted Oct 19, 2009, 11:04 AM
Here is Explanation How i Done it ( I added comment in code to explain it :)
friend, dont forget to mark "do you like this answer" if my answer helped you :)
First on Form I taken one Label Called Label 1 and Made it Public :)
Now Code Like Below in MyClass and Form1
MyClassCode
------------------------
namespace WindowsFormsApplication8
{
class MyClass
{
public void ChangeTheLabel()
{
//Locate the Running Intance of Form1
Form f = Application.OpenForms["Form1"];
//Here i can Access Label1 Because i have made it Public in Form1
((Form1)f).label1.Text = "Testin OO Concepts ";
}
}
}
Form1 Code
--------------
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Instantiate the MyClass
MyClass m = new MyClass();
//Call the Method to change the label
m.ChangeTheLabel();
}
}
}
so its not breaking any oops concepts and works well .
also you can do this by defining propertiy but it can be simply done as above code :)