Conditional inclusion of usercontrols in ascx file

  • Thread starter Thread starter Daisy
  • Start date Start date
D

Daisy

I've got lots of user controls that include other user controls like this:

<uc1:MyControl runat="server" UserKey="<%# User.Key %>"></uc1:MyControl>

and I'm calling .DataBind() on the page at the end. All work great, sweet.


Now I've got a situation where User is null, and the above example fails
(NullReference). I've tried setting Visible="False" and the DataBinding
still seems to fire and the exception thrown, and I can't Remove the control
from the page because the User object isn't created until inside
base.DataBind() anyway, so before, it's always null, and after, the
exception has already been thrown.

What's the best way to have this control not appear, if User is null,
*without* creating the whole thing programatically with LoadControl (I've
moved away from that after a disasterous start to .NET doing everything
programatically!).

Thanks
 
Justin Rogers said:
I'd recommend handling the null case in your property (UserKey)

If User is null, databinding to User.Key throws an exception, it can't be
done in the property.

Anyways, the way I got around it was to override DataBind and only call
base.DataBind if user exists. If not, I don't want it (or any child
controls) to b bound. :-)
 
Back
Top