Yesterday, I mentioned how excited I was that I could use a cereal reference to describe programming. I am lucky to be working with a dev who’s learning ASP.NET, and there are times where things that come easily for me don’t necessarily come easier for her.  The reason why I say I’m lucky in that case is because I love being able to show people new things, especially when it comes to code.  I also have realized over the years that I have a special skill of being able to explain code in simple terms.

So this week’s conversation was about using an ASP.NET repeater and accessing controls within the ItemTemplate during ItemDataBound.  It can be a tough concept to understand, so I had to find a good analogy to get the short point across.  Sure, she could’ve followed the code I had for other pages, but I’d rather have her understand why rather than blindly copy-paste-and-adapt. So here’s how our conversation went…

Her: Why can’t I access these controls?

Me: Which?  <looks at her screen> Oh… these controls in the repeater ItemTemplate?

Her: Yeah.  I know I need to do this at ItemDataBound, but I can’t see the control.

Me: Think of it like a box of Lucky Charms. Those controls are like marshmallows.

Her: <puzzled look>

Me: As a developer, we can physically see the controls in the code.  Just like when we open a box of Lucky Charms – you can see the marshmallows in the bag of cereal.

However, you can’t just take the marshmallows out of the box.  There’s the cereal bag that holds them.

Her: <following what I’m saying so far>

Me: The ItemTemplate is like that cereal bag.  Those controls are in a container and you can’t just take them out.  You need to get to them by going through the container.

So e.Item is your container.  And to find that control that you need to populate, you’d tell the container e.Item.FindControl(“name of control”).

Her: <nods, understanding my random cereal analogy>

While the cereal box analogy can’t be used for everything, it helped in this case.

By sadukie

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.