One useful little control we wrote for ASP.NET is our BindOnPreRender control. It simply calls DataBind() on itself at PreRender.
Its utility may not be obvious. This is sort of related to my post on WebForms DataBinding. Binding is better. It lets us bind properties to objects in our markup, which helps reduce code-behind. I’m not totally against code-behind, but I do rather like binding expressions.
Binding with Binding Expressions typically only happen inside repeater-like data controls. But they can be used anywhere. The problem is that binding expressions only get invoked when DataBind() is explicitly called. And if you have to do that, well, then you’re not really reducing code-behind, you’re actually increasing complexity.
Enter this little control
public class BindOnPreRender : Control
{
private bool _needsDataBinding = true;
public virtual bool NeedsDataBinding
{
get { return _needsDataBinding; }
set { _needsDataBinding = value; }
}
protected override void DataBindChildren()
{
if (Visible)
base.DataBindChildren();
}
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
NeedsDataBinding = false;
}
public virtual void EnsureDataBound()
{
if (NeedsDataBinding)
DataBindChildren();
}
protected override void OnPreRender(EventArgs e)
{
EnsureDataBound();
base.OnPreRender(e);
}
protected void Page_PreRender(object sender, EventArgs e)
{
EnsureDataBound();
}
}
And the usage is like this:
<uc:BindOnPreRender runat="server"> <asp:TextBox runat="server" Text='<%# MyFancyPageMethod() %>' /> </uc:BindOnPreRender>
Be careful about wrapping this around controls that already do the whole “bind on prerender” thing, such as ListView, GridView, etc.
Discussion
No comments for “BindOnPreRender Control”
Post a comment