Cageman
Cageman

Reputation: 523

Call parent from custom control

I have a form, on this form is a flowlayoutpanel with multiple custom made TextBoxes The form overrides the base methode Refresh(), to do some other things also. Now I'm digging into the parent to eventueally come on the form and do the refresh

this.Parent.Parent.Parent.Refresh();

I want to re-use the control on other forms, so is there another way to do this?

And I know a While(true) is possible:

Boolean diggToParent = true;
var parent = this.Parent;

while (diggToParent)
{
    if (parent.Parent != null)
    {
        parent = parent.Parent;
    }
    else
        break;
}

parent.Refresh();

But is there a cleaner way to do this?

Upvotes: 0

Views: 82

Answers (1)

Markus
Markus

Reputation: 22456

You can solve this by creating and raising an event that is handled by the parent form:

public class MyUserControl : UserControl
{
    // ...

    public event EventHandler RequestRefresh;

    // Call this method whenever you want the parent to refresh
    private void OnRequestRefresh()
    {
        if (RequestRefresh != null)
            RequestRefresh(this, EventArgs.Empty);
    }
}

In the parent form (or the container that should be refreshed), you add an event handler, e.g.

public class MyParentForm : Form
{
    public MyParentForm()
    {
        InitializeComponent();
        userCtrl.RequestRefresh += userCtrl_RequestRefresh;
    }

    // Do whatever the parent thinks is necessary to refresh.
    public void userCtrl_RequestRefresh(object sender, EventArgs e)
    {
        Refresh();
    }

    // ...
}

This way the parent form can decide what to do when the user control requests a refresh. For details on events, see this link.

Upvotes: 1

Related Questions