Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing parent control from child control - ASP.NET C#

Tags:

c#

asp.net

I have a parent user control with a label. On the parent's OnInit, I dynamically load the child control. From the child control, I will need to set the parent's label to something.

Using the Parent property returns the immediate parent which is actually a PlaceHolder in my case. Theoretically, I can recursively loop to get the reference to the Parent User control. Am I heading in the right direction here? Is there a straightforward way of doing this?

like image 607
DotnetDude Avatar asked Mar 30 '09 18:03

DotnetDude


4 Answers

@Rex M has a good and easy solution for this and just to expand on it to show the usage:

This code snippet is used from within the child user control to access parent user control property:

((MyParentUserControlTypeName)NamingContainer).Property1 = "Hello";
like image 78
Art Avatar answered Nov 13 '22 10:11

Art


Try getting the child's NamingContainer.

like image 26
Rex M Avatar answered Nov 13 '22 11:11

Rex M


Or you could iterate through the parents until you find the desired control, such as with an extension method.

public static Control GetParentOfType(this Control childControl,
                                   Type parentType)
  {
      Control parent = childControl.Parent;
      while(parent.GetType() != parentType)
      {
          parent = parent.Parent;
      }
      if(parent.GetType() == parentType)
            return parent;

     throw new Exception("No control of expected type was found");
  }

More details about this method here: http://www.teebot.be/2009/08/extension-method-to-get-controls-parent.html

like image 4
teebot Avatar answered Nov 13 '22 12:11

teebot


To me the right way to do this is by exposing an add method in the control. Now if you need to update a label outside it, expose an event, something like OnCollectionChanged(...) and suscribe from the control that will need to show info about the collection.

This way each control does it's part and all stays SOLID

like image 1
Aridane Álamo Avatar answered Nov 13 '22 12:11

Aridane Álamo