Prevent nullrefs when databinding with placeholders

Posted by Robin Hermanussen on April 10, 2011 · 2 mins read

I love databinding. It allows me to keep view-logic in ascx/aspx files so I don’t have to read long code-behind files laden with initialization logic and page lifecycle related crap.

Databinding works better with WPF and Silverlight than it does with ASP.NET. But in my humble opinion it still beats the alternative in ASP.NET.

One very annoying problem I’ve run into when using databinding in ASP.NET is the use of placeholders. The placeholder is a control that we use as the equivalent of an if-statement in C#. If the “Visible” property evaluates as true, only then the contents are rendered.

This works well in most cases. But when you use databinding it sort of breaks. For example:

This code will work perfectly fine, unless “SomeProperty” evaluates to null, because the contents of the placeholder are always evaluated! This problem is especially annoying with Sitecore FieldRenderers, which don’t allow the “Item” property to be null. A simple fix to this problem is to repeat the null-check within the placeholder, like so:

But if you would have a more complicated condition, many unsafe binding statements within the placeholder or nesting of several placeholders, this fix can prove to be quite cumbersome.

So I tried to find a good workaround for this problem and I observed the repeater control. It does not have this problem, because the contents of “ItemTemplate” will never be evaluated if the collection in the datasource is empty. This is what I came up with:

That works really well! I used the repeater as a placeholder and now, if “SomeProperty” evaluates to null, there will be no problem; the contents of “ItemTemplate” are never evaluated by the databinder.

Still, this is quite an ugly workaround, because it’s pretty verbose and not really intuitive to programmers. So we need a better solution.

And I found one! I created a custom control that derives from the PlaceHolder control. The only difference in behaviour is that the contents of the control are not evaluated by the databinder if the “Visible” property is null. Here’s the code for the control:

This is a pretty simple change, but it makes life so much easier. If we import the control and use it in the following way, we no longer have to worry about nullref problems:

Happy coding!