AMP said:
Hello,
Where can I find a GREAT explanation about keeping references to other
classes/forms between each other.
I'd like to see code that uses the different methods , public
properties, set-get.
Am I correct in saying one form or class has to instantiate the other
one for this to work?
Thanks
Mike
Hi Mike,
GREAT examples pretty much depend on what you already know and what you
don't know, but below are some examples of using a windows form and a class
and how they may interact. One example uses DataBinding as well, just to
show you can have a control and an object interact behind the scenes. You
should however wait using DataBinding until you are more comfortable of how
winforms work as DataBinding errors can be very cryptic and difficult to
solve.
The examples assumes you have created a windows application project.
Replace everything except the 'using' lines at the top of the code file.
public partial class Form1 : Form
{
private MyObject instanceOfMyObject;
public Form1()
{
Button button1 = new Button();
Controls.Add(button1);
button1.Click += new EventHandler(button1_Click);
}
protected override void OnLoad(EventArgs e)
{
instanceOfMyObject = new MyObject();
instanceOfMyObject.InstanceString = "Hello World";
MyObject.StaticString = "Static stuff";
}
private void button1_Click(object sender, EventArgs e)
{
using (MyDialog dialog = new MyDialog(instanceOfMyObject))
{
dialog.ShowDialog();
MessageBox.Show(instanceOfMyObject.InstanceString);
}
using (MyDialog dialog = new MyDialog())
{
dialog.DisplayText = MyObject.StaticString;
dialog.ShowDialog();
MessageBox.Show(dialog.DisplayText);
}
}
public class MyDialog : Form
{
private TextBox textBox1;
public MyDialog()
{
InitializeComponent();
}
public MyDialog(MyObject myObject)
{
InitializeComponent();
textBox1.DataBindings.Add("Text", myObject, "InstanceString",
false, DataSourceUpdateMode.OnPropertyChanged);
}
private void InitializeComponent()
{
textBox1 = new TextBox();
Controls.Add(textBox1);
}
public string DisplayText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
public class MyObject
{
private string _instanceString;
private static string _staticString;
public static string StaticString
{
get { return _staticString; }
set { _staticString = value; }
}
public string InstanceString
{
get { return _instanceString; }
set { _instanceString = value; }
}
}
}