Wednesday, 2 April 2008

DataBinding woes

I tore my hair out over this one, for hours. And the solution to the problem was so simple I felt stupid not to realise what was going on.

I have a custom server control called CustomerSummary. It has a single public Customer property that can be set declaratively on any page where it is used. I use this control in three different web applications, and implementing it in the first two was no problem. But when it came to the third application, the control never rendered. I just could not figure it out.

While debugging the control I realised that the Customer property was never set, even though it was correctly declared on the page with Customer=’<%# CurrentCustomer %>’ (CurrentCustomer is a property on the containing page’s code-behind). What the?

After much poking around and debugging a colleague looked at it and said: “Do you call DataBind() on your page?”. No, I don’t. And that’s why. The <%# %> expression is a databinding expression, so since the page didn’t call DataBind(), the CustomerSummary control was never bound to the customer data, and therefore never displayed.

So the first solution was to call DataBind() in the Page_Load method (this is what the first two applications do; that’s why it worked there). However, the same colleague that pointed out that DataBind() was missing pointed me to this article which explains custom code expression builders and how you can use them to avoid having to call DataBind() and bloating the ViewState. Sweet! It’s recommended reading.

No comments: