Search code examples
c#winformsvisual-studio-2010controlsparent

var this.Parent as STP2Main better syntax


I have a controll which has the following function if I load the control into form A.

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

if i load the control into form B I need this to write this:

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

this works. but I really do not like the this.Parent.Parent... (up to 5 times Parent) If i set a breakpoint on the var C line I see it is pointing to [STP_Design.STP2Main] but when I change the function to var C = STP_Design.STP2Main as STP2Main; I get an error which says:

'STP_Design.STP2Main' is a 'type', which is not valid in the given context

How do I get rid of the Parent.Parent.Parent part?


Solution

  • If the parent control is a Form you could use

    var C = this.ParentForm as SomeControlName;
    

    I hope this helps.