August 26, 2009

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

(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:



The ASP:


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:




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:



kick it on DotNetKicks.com

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete