Databinding Protips Part 1: DataBinding 101

What is wrong with this code?

ASPX file:

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


 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.


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


 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.

if you like it.


Category: Time: 2007-09-24 Views: 1

Related post

  • Sql Server Full-Text Search Protips Part 1: Setup 2006-11-12

    As I have previously mentioned, Sql Server's Full-Text search can let a developer create some very slick features disturbingly easily. And, unlike many other Full-Text implementations, it is not limited to plain text fields. It can also search within

  • Sql Server Full-Text Search Protips Part 2: CONTAINS vs. FREETEXT 2006-12-06

    In Part 1 of this series we explored the methodology for enabling a Sql Server database for Full-Text Indexing and enabling Full-Text indicies on specific tables. But now we get to the good part-how to use that index in your application. There are fo

  • Sql Server Full-Text Search Protips Part 3: Getting RANKed 2006-12-30

    In Part 1 of this series we explored the methodology for enabling a Sql Server database for Full-Text Indexing and enabling Full-Text indices on specific tables. And in Part 2 of this series we explored the methodology for accessing these Full-Text i

  • Android dataBinding - unable to notify view of changes 2016-01-28

    i am trying to use databinding for a purpose. I have a project i've created that starts a countdown timer. If the time is a prime number it should update a TextView in a xml layout. The timer works fine but the textview never gets updated. here is my

  • What package does org.core.databinding belong? 2011-06-17

    One of my applications requires org.eclipse.core.databinding but I can't seem to a package to install that satisfies this requirement. Does anyone know how to find and install this (if it requires anything more than a using Install New Software). ---

  • whats the difference between 101 and 102 key keyboards, and which do i need for UK laptop 2010-05-05

    I want to replace the US keyboard on my laptop with a UK one. I thought that UK keyboards were 102 and US were 101 as my Uk one has a (#) key and the US one doesn't. But the UK replacement part keyboard specifies 101 keys, so I am now confused. Can s

  • How to separate Title and Url from hyperlink field? 2013-10-15

    I have created a column which is of type Hyperlink or Picture. I want to display the list of links in web part, in such a manner that title should appear as text and the Url should be bound in that text i.e. href=Url. My code is: protected void Page_

  • Unable to export Eclipse RCP application as a product 2016-01-26

    I have an application which I want to export as a product. For that purpose I have create a product for my RCP application. While creating the product definition, I have chose the Application as EditorApp.application. Added EditorApp(My application)

  • Log files are not generated while running RCP product file 2016-02-02

    I have a RCP application in which I am using log4j for logging purpose. For that I have added log4j jar in MANIFEST.MF file. and also added under the root folder. But, when I am starting the application (after export the product), (w

  • Knockout : Observable with Observables inside only updating in UI, but unchanged when passed to the server? 2016-02-08

    I have this observable object, which has two observable properties inside : self.matchModel = ko.observable(); The Model looks like this : function toKnockOutObservable(data) { return { Id: data.Id, TeamId: data.TeamId, TeamName: data.TeamName, Oppon

  • Is it wrong to stick to a platforms' or technologies' core principles and paradigms? [on hold] 2016-03-02

    I've recently switched jobs and came into a new team with two senior and another new developer. I have a couple of years of experience with developing, shipping and maintaining software. We're tasked with the development of a fairly large application

  • Custom App Page Change Site Title, pass new Title value 2011-01-28

    I created a custom app page with two user controls: asp:TextBox ID="SiteTitle" runat="server" and asp:Button ID="UpdateSubmit" runat="server" Text="Update" The goal is to have the same behavior as the _lay

  • Documenting server details 2012-03-01

    This could be a very naive question for many of you, but I have problem in answering this one, your help will be deeply appreciated. I need to document the server on which I work, and it should include following heads: IP address -> Model-> (Dell...

  • Does bcache support use of an LVM logical volume as a cache device? 2015-01-15

    I've got a 64GB SSD and a 3TB hard drive in my system running Ubuntu 14.04. The SSD has a small root partition with rest of the device allocated to an LVM physical volume. From that LVM physical volume I have two logical volumes allocated, one for /u

  • Why are my sounds lagging on my 13" Macbook Pro? 2015-04-19

    System information: 2.4 GHz Intel Core i5, 8GB 1600 MHz DDR3 memory, running on Yosemite 10.10.3, 2014 Macbook pro retina model Sound on my computer keeps lagging, but not sound on videos or anything like that. If I get an iMessage to my computer, I'

  • Barcodegolf: Generate a number's UPC 2015-08-15

    Just about every store nowadays uses Universal Product Code (UPC) barcodes to simplify the checking out process. If the name doesn't mean anything to you, you will surely recognize what they look like: Format The most common system is UPC-A, which us

  • Data binding errors in layout file Android 2016-01-27

    I have got below error in Android studio: Error:(12, 42) error: package cloudwell.collectorapp.databinding does not exist D:\Ismail\CollectorApp\app\src\main\java\cloudwell\collectorapp\services\ D:\Ismail\CollectorApp\a

  • gradle cannot resolve dependencies for android project 2016-02-10

    The Problem is that gradle cant find the jars for the dependencies, but gradle is looking on the wrong place. Gradle keeps searching for the files in the wrong directory ( the directory where the Google & Android support libary resides.... Searched i

  • Possible to DataBind to a SPListItem URL? 2011-05-20

    I have a ListView that I am binding to a SPList. In this list view I would like to have a link to each SPListItem. Microsoft has conveniently decided that the URL member of an SPListItem should be a mysterious link that does not work. After some rese

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.565 (s). 13 q(s)