I have a child form which has a find form in it. I set the find form’s owner to the child form like so:
private void ShowFindForm()
{
FindForm.Show(this);
}
which then allows me to access it’s properties like this:
private void FindNext()
{
TreeNode matchingNode = ...
... etc
... etc
OwnerForm form = this.Owner as OwnerForm;
form.TreeView.SelectedNode = matchingNode;
}
This works perfectly fine until I shove the owner form into an MDI form, whereby the MDI form promptly takes ownership of the find form and messes it all up. How do I get around this?
UPDATE:
I can hack around this by iterating through the MDI form’s MdiChildren property until I find the form I want, but this seems a bit cowboy-ish.
A simple solution to this problem is to create a public
OwnerFormproperty on your child form like this:and then edit your
ShowFindForm()method to this:and then change the second-to-last line in your child form’s
FindNext()method to this:myOwnershould probably actually be a private property with public get and set methods, but this is just to illustrate the principle. Basically, instead of assuming that your child form’s Owner is the form whose properties you want to access (an assumption that breaks in the MDI world, as you’ve found), you’re explicitly creating a reference to the form you want.As a side note, many would consider your code sample to be a violation of the OOP principle of encapsulation, since you’re manipulating one form’s controls from another form. I’ve seen worse crimes against humanity, myself.