Click here to Skip to main content
15,889,808 members
Articles / Desktop Programming / MFC

We Don't Usually Know What Kind of Parents Had Our Grandparents

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
5 Mar 2010CPOL 7.4K   1  
(or How to Retrieve a Type of Parent Control Using an Extension Method)Here's a situation where I had to retrieve the next Parent Control of a certain type.

(or How to Retrieve a Type of Parent Control Using an Extension Method)

Here's a situation where I had to retrieve the next Parent Control of a certain type. In this particular case, my label is included in an UpdatePanel to update only when my Label is assigned a new value.

I could have used the Parent attributes of my controls and go up a few levels until I have the right one:

ASP.NET
<textarea name="code" class="c#" cols="60" rows="10">
UpdatePanel updatePanel = label.Parent.Parent;
updatePanel.Update();

</textarea>

The ASP:

ASP.NET
<textarea name="code" class="c#" cols="60" rows="10">

<asp:updatepanel id="UpdatePanelMessage" runat="server" updatemode="Conditional">

<asp:label id="LabelMessage" runat="server" resourcekey="labelErrorResource1">

</textarea>

Do you see what's wrong?

And what if the page is modified and the control is included in a new div or in a new panel? You see it coming, the control retrieved won't be an UpdatePanel because we don't usually know what kind of Parents had our Grandparents... So as soon as the asp page structure changes, chances are that casting errors start to appear.

We need a way to look up that control's ancestry and return the first parent of a certain type. We can achieve that by using the following extension method:

<textarea name="code" class="c#" cols="60" rows="10">
C#
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");
}
</textarea>

Now wherever we need to retrieve the first occurence of any control's parent of a certain type we just call the method GetParentOfType this way:

C#
<textarea name="code" class="c#" cols="60" rows="10">

UpdatePanel updatePanel = (UpdatePanel)label.GetParentOfType
(typeof(UpdatePanel));
updatePanel.Update();

</textarea>
This article was originally posted at http://www.teebot.be/feeds/posts/full

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Logica
Belgium Belgium
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --