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?
@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";
Try getting the child's NamingContainer.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With