Mosh-Production's Blog

May 3, 2009

Conditional Rendering

Filed under: Coding Horror — Shani Natav @ 10:20 pm
Tags: , , , ,

Hi folks!

Just learnt how to use this awesome blogging tool! 🙂
opened up a new user name and I’ll be writing most of my posts using this user.
This time i’ll blog about conditional renderer Custom Control I prorgammed. Sort of.

For my first Post I chose a control I recently made up, that renders a bunch of controls (like maor loves saying ‘bochta’) only if a certain value is not empty or null. You know those pesky fields that get rendered in the middle of your form, and you want to make them disappear with the label? Then it’s this.. :).

The code will be hopefully attached, Just a little example before I finish off and go to sleep:

<Myc:ConditionalRenderer runat="Server" ID="freqsContiditonal" FieldValue="<%# YourFieldParameterGoesHere %>" >
<td style="background-color:White;font-size:10pt;text-align:left;">
Value: <%# Container.FieldValue %>

And the Awesome source code:

using System.ComponentModel;
using System;
using System.Collections;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyControls;


namespace ControlORama
public partial class ConditionalRenderer : WebControl, INamingContainer
private ITemplate _renderTemplate;

public string FieldValue

public event EventHandler ValidateValue;
public void OnValidateValue(object sender, ValueValidationEventArgs e)

private bool instanciated = false;

protected override void EnsureChildControls( )

var field = FieldValue;
if (ValidateValue != null) {
var args = new ValueValidationEventArgs(field);
ValidateValue(this, args);
if (args.Cancel)
if (string.IsNullOrEmpty(field))

instanciated = true;

protected override void Render(HtmlTextWriter writer)
if (instanciated) {
foreach (var item in Controls.OfType()) {

[Browsable(false), Description(“Template to render”), TemplateContainer(typeof(ConditionalRenderer))
, TemplateInstance(TemplateInstance.Multiple)
, PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate RenderTemplate
get { return _renderTemplate; }
set { _renderTemplate = value; }



1 Comment »

  1. Dont forget to perform DataBinding on the Control:


    Comment by moshproduction — May 4, 2009 @ 12:34 pm | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: