Databinding Protips Part 1: DataBinding 101

Share this article

What is wrong with this code?

ASPX file:


<p>
    The time is now <asp:Literal runat="Server" ID="TimeContainer" />.
</p>

Codebehind:


protected override void OnLoad(EventArgs e)
{
    TimeContainer.Text = DateTime.Now.ToString();
}

Technically nothing. But in terms of writing solid, maintainable applications there is a big issue. If you ever want to change that interface text, you probably need to get a programmer and modify the codebehind. Depending on which sort of ASP.NET project you used, you might well have to go through a full redeployment as you will have to recompile the application to change a few words in the UI. This is a bit too much work, and too much risk for my tastes.

There is, however, a better way: Declarative DataBinding.

ASPX:


<p runat="Server" id="DataBindingContainer">
The time is now <%# CurrentDateTime.ToString() %>.
<br />
And the current longdate is <%# CurrentDateTime.ToLongDateString() %>.
</p>

Codebehind:


protected override void OnLoad(EventArgs e)
{
    DataBindingContainer.DataBind();
}

protected DateTime CurrentDateTime
{
    get { return DateTime.Now; }
}

There are a few things to note about the codebehind here. First is the call to DataBindingContainer.DataBind(). This is because you must make a call to DataBind() the container with any declaratively bound elements. Second is to note how we made a protected property for the CurrentDateTime. We could have bound to directly DateTime.Now, but I chose to show this as a protected property for a reason: DataBinding actually occurs in a system-generated class that inherits from your page, so anything called from the ascx template must be accessible to that class; private variables need not apply.

You might wonder why I stuck in the 2nd databound expression, and the reason is simple: to show that you can call any method on any object you are databinding to, not just the basic ToString() call. These are strongly typed calls to fully-fleged objects, so you can call anything you could call in your codebehind.

That is pretty cool Wyatt, but what if I want to have some logic in there?

Then you need to meet our new friend, the ternary operator:

<p>Daylight savings time <%# CurrentDateTime.IsDaylightSavingTime() ? "is" : "is not" %> in effect.</p>

This is a very handy bit of syntactic sugar that lets one compress a simple if statement down to a single line. The above example would translate to:

private string GetDaylightSavingsStuff()
{
    if (CurrentDateTime.IsDaylightSavingTime())
    {
        return "is";
    }
    else
    {
        return "is not";
    }        
}

You could also use this tactic to set visible properties on server controls. For example, let’s say we wanted to make a little announcement if it is, in fact, a weekend:

<asp:PlaceHolder runat="Server" ID="DataBindingContainer">
    <p>The time is now <%# CurrentDateTime.ToString() %>.</p>
    <p>Daylight savings time <%# CurrentDateTime.IsDaylightSavingTime() ? "is" : "is not" %> in effect.</p>
    <p runat="Server" id="Weekend" style="font-weight:bold; color: red" visible='<%# CurrentDateTime.DayOfWeek == DayOfWeek.Saturday || CurrentDateTime.DayOfWeek == DayOfWeek.Sunday ? true : false %>'>
        ITS THE WEEKEND! What are you doing coding man!
    </p>
    <p runat="server" id="Weekday" style="font-weight:bold; color: blue" visible='<%# CurrentDateTime.DayOfWeek == DayOfWeek.Saturday || CurrentDateTime.DayOfWeek == DayOfWeek.Sunday ? false : true %>'>
        ITS A WEEKDAY! Get back to work man!
    </p>
</asp:PlaceHolder>

Now, at this point, you are wondering exactly what to do in your templated controls, such as the Repeater or the GridView. And, for that gem of knowledge, you should stay tuned for DataBinding Protips Part 2: Using DataBinder.Eval for Fun and Profit.

Want to play with the code used for the examples above? Get the codes man.

kick it on DotNetKicks.com if you like it.

Wyatt BarnettWyatt Barnett
View Author
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form