Accessing function and elements from one form on other

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have two window app. I have Tree in main window and in code of that window
I have function BuildTree(); This function start with tree.Clear(); So it
completely rebuild tree. When I open other window as dialog after clicking on
`Save` button I whant call BuildTree() function. Sorry, I am jus a biginer.
How am I suupoused to do that? An yet I whant change lable text on main
window. How to access lable control on main form from dialog window?

Thanks in advance
 
Hi Sergey,

The dialog needs to have a reference to the main form.
If you create the Dialog from MainForm you can add an overloaded constructor accepting a MainForm parameter

// in MainForm
Dialog d = new Dialog(this); // this would be MainForm
d.Show()
....
// in Dialog
public class Dialog
{
private MainForm parent;
public Dialog(MainForm m)
{
parent = m;
}
}

Then, whenever you need to do something on MainForm, like calling BuildTree you can do

parent.BuildTree();

If when clicking Save you also close the Dialog a better way would be to expose properties in the Dialog that MainForm uses

//in MainForm
Dialog d = new Dialog();
if(d.ShowDialog() == DialogResult.Yes)
{
// access properties of the Dialog if necessary
BuildTree();
}

// in Dialog
private void buttonSave_Click(object sender, EventArgs e)
{
// if you have assigned a dialogresult to the button you can simple close the form
// otherwise you will have to set it now
this.DialogResult == DialogResult.Yes;

// any resulttype would work as long MainForm knows it
this.Close();
}
 
The easy and ugly way for doing so is to make public properties and methods
in the main window, and then pass a reference to the main window instance to
the dialog (so that you create a constructor that takes a main form instance
in that dialog), from which you call upon the functions you want in main
form.

However, there are better and more respected ways. The point is that you
must try to hide main form from the dialog, while still being able to
actually access it.
Let's say that you define an interface that the main form implements:

interface ITreeForm
{
// Method for modifying label's text.
void SendMessage(string text);

// Method for rebuilding the tree.
void BuildTree();
}


So that you could define the code for dialog's constructor:

// a local var to keep the form around:
ITreeForm form = null;

public MyDialogCtor(ITreeForm treeform)
{
form = treeform;
}

// The save method
void Save()
{
// do your saving..
...
// and then call upon the interface..
if ( ITreeForm != null )
{
form.BuildTree();
form.SendMessage("Whatever");
}
}

Implementing this interface by the main form means that any other form can
call functions on it whithout knowing that it is actually, "the main form".
Thus you can pass the interfce reference around.
 
Back
Top