# better way to write this function [closed]

I have a user control which I load into different flowlayoutpanels, on different forms etc.

In this user control i have a function like this:

private void button1_Click(object sender, EventArgs e)
{
var C = this.Parent.Parent.Parent.Parent.Parent as STP2Main;
C.DisposeControl(STP_Data.Data.ConfigConfigResource);
}


But how many times I need Parent is dependant on the form I load the control in. So I want to do that on a better way. it is reffering to STP_Design.STP2Main, but when I replace this.Parent etc. with STP_Design.STP2Main I get this error: 'STP_Design.STP2Main' is a 'type', which is not valid in the given context

Any tips?

-

## closed as off topic by ANeves, Trevor Pilley, Jeff Vanzella, svick, CorbinNov 15 '12 at 4:01

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

I don't know if it helps in your case, but you can find the form that contains the (possibly nested) control with the FindForm method of the control. –  Olivier Jacot-Descombes Nov 13 '12 at 16:05

private IEnumerable<Control> EnumerateParents()
{
var parent = Parent;
while (parent != null)
{
yield return parent;
parent = parent.Parent;
}
}

private void button1_Click(object sender, EventArgs e)
{
var c = EnumerateParents().OfType<STP2Main>().First();
c.DisposeControl(STP_Data.Data.ConfigConfigResource);
}

-