WynApse Home Page
Home    Blog    About    Contact       
Latest Article:

My Tags:
My Sponsors:

Lifetime Member:

Server-Side Code used in DataList ItemTemplate

I don't know why I didn't think of it a year ago, but when I got my blog space at geekswithbogs.net, I jumped right on adding links to the left-border of the page. The "why didn't I think" part is I could have done that to my site. I only had two sets of links, one that became a mirror of what is displayed in my BlogRoll and the other was a stale list of web sites.

I decided I wanted to either move or copy (haven't decided which yet) the entire list of links from geekswithblogs over to my site sidebar. That meant I needed a good way to update/delete items from the web as well. Since I already have an Admin page for adding onto my BlogRoll, I just added a few more tables and a few more sections to my sidebar.

The Challenge

Of course there had to have been a challenge or else why would I be writing about it. I really like the way geekswithblogs has their links setup with showing the web link to the rss feed if you enter one. If there is a feed, the hyperlink is followed by a hyperlink to the rss feed like this: "(rss)".

I didn't want to deal with that immediately, but I knew where I could find it, so I just added an rss field to each table, and an rss entry box on my form for each link of any type.

Once I had the entry page all working, and populated with all the sites from my blog page, I pulled out Scott Mitchell's ASP.NET Data Web Controls Kick Start, and found what I needed pretty quickly.

Conditionally Changing the DataList ItemTemplate

It's simple to add the (rss) link in and have an empty link just be a link back to your page, but who wants that? I wanted the (rss) to only appear if there was a valid rss feed listed in the database just like geekswithblogs does. To do that, you have to get the host server code into the activity, but not much.

I added one method to my page code:

    public string FormatRSS(object _rss)
        if (_rss.Equals(DBNull.Value))
            return "";
        else if (_rss.ToString() == "")
            return "";
            return " (<a href=\"" + String.Format("{0}", _rss) + "\">rss)";

Then the ItemTemplate got this addition tacked on the end:

<%# FormatRSS(DataBinder.Eval(Container.DataItem, "rss")) %>

And that is all it took. Since the rss field was already in each table, simply adding that piece of code to the end of every ItemTemplate made all the links work just as I wanted.

Thanks Scott!
Copyright © 2006-2022, WynApse