Click here to Skip to main content
Licence CPOL
First Posted 23 Oct 2007
Views 27,570
Downloads 108
Bookmarked 61 times

RSS/XML Data-Binding to Data Control with Row Limitations

By | 23 Oct 2007 | Article
This article not only details how to bind an RSS feed (or any XML document) directly to a data control (DataGrid), but also how to limit the number of rows displayed

Introduction

This code will use an RSS feed as a data source for a DataGrid control. Instead of displaying all rows in the feed, row-limiting code is also used.

Background

I built a SEO CMS for the company I work for. One of our clients wanted to include dynamic RSS data on output pages. Since the system can output the entire site to any server environment, this was simple. In this case, the client's ASP.NET environment would be able to handle the dynamic data, as the .NET code could be placed directly in their Web page templates, as the system does not compile any code, only outputs pages.

Binding an RSS feed to a data control is simple, right? What about if you don't want to display all the rows of that feed? Let's say, for a Web site, you have found the perfect feed that will add SEO content to a given page. As not to dilute the content's importance, you only want to display two or three RSS articles from that feed, and not all 15-30.

Using the Code

The following code can be placed entirely on the *.aspx page, but can also be moved to a code-behind page.

We will use System.Data and System.Xml to parse and manipulate the data from a given RSS feed.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>

Next, after indicating the script language, we define the feed and the number of articles to display from the feed.

<script language="C#" runat="server">
    
    const string RSS_FEED = "http://news.google.com/news?hl=en&ned=us&ie=
            UTF-8&q=Living+room+entertainment+furniture&output=rss";
    const int MAX_RSS_ROWS = 2; 

The code to process the RSS feed is contained in GetRSSFeed(). We are not at all concerned about parsing any of the feed, as the XmlTextReader does all of the work for us. After loading the feed, we create a DataSet with the feed data.

Usually, we would just end here, return the DataSet, and bind to our data control. However, what we want to do is limit the amount of data that is actually displayed by the data control.

I did think about using the DataGrid's paging option, and through CSS, setting the paging display index to 'none' - but that's messy.

The next step involves populating a DataView, so we can cycle through the view's rows, and creating a new DataTable, which will contain the limited data set.

protected DataTable GetRSSFeed(string strURL)
{
    XmlTextReader reader = new XmlTextReader(strURL);

    DataSet ds = new DataSet();
    ds.ReadXml(reader);         // populate dataset
        
    // populate dv so we can filter out extra <item> rows
    DataView dv = new DataView(ds.Tables[3]);
    DataTable outputTable = dv.Table.Clone();
        
    // iterate through the dv rows, copy them to the outputTable 
    // until max rows is reached
    for (int x = 0; x < MAX_RSS_ROWS; x++)
    {
        outputTable.ImportRow(dv.Table.Rows[x]);
    }

    return outputTable;
}

The Page_Load() method calls our GetRSSFeed() method, which returns the data source for our DataGrid:

protected void Page_Load(object sender, EventArgs e)
{
    recentPosts.DataSource = GetRSSFeed(RSS_FEED);
    recentPosts.DataBind();
}

Finally, we need to define the DataGrid, and data items to display:

<asp:DataGrid runat="server" id="recentPosts" AutoGenerateColumns="False"
     Font-Name="Arial" Font-Size="10pt"
     HeaderStyle-Font-Bold="True"
     HeaderStyle-HorizontalAlign="Center"
     HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White"
     HeaderStyle-Font-Size="15pt"
     AlternatingItemStyle-BackColor="#eeeeee" AllowPaging=false Font-Names="Arial" PageSize="3">
  <Columns>
    <asp:TemplateColumn HeaderStyle-BackColor="Gray" HeaderText="RSS FEED">
      <ItemTemplate>
        <a href="<%# DataBinder.Eval(Container.DataItem, "link")%>">

That's it!

Simply copy/paste the code below into a new *.aspx page. The entire code for the page reads as follows:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>

<script language="C#" runat="server">
    
    const string RSS_FEED = "http://news.google.com/news?hl=en&ned=us&
            ie=UTF-8&q=Living+room+entertainment+furniture&output=rss";
    const int MAX_RSS_ROWS = 2;

    protected void Page_Load(object sender, EventArgs e)
    {
        recentPosts.DataSource = GetRSSFeed(RSS_FEED);
        recentPosts.DataBind();
    }

    protected DataTable GetRSSFeed(string strURL)
    {
        XmlTextReader reader = new XmlTextReader(strURL);

        DataSet ds = new DataSet();
        ds.ReadXml(reader);         // populate dataset
        
        // populate dv so we can filter out extra <item> rows
        DataView dv = new DataView(ds.Tables[3]);
        DataTable outputTable = dv.Table.Clone();
        
        // iterate through the dv rows, copy them to the outputTable 
        // until max rows is reached
        for (int x = 0; x < MAX_RSS_ROWS; x++)
        {
            outputTable.ImportRow(dv.Table.Rows[x]);
        }

        return outputTable;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>RSS</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:DataGrid runat="server" id="recentPosts" AutoGenerateColumns="False"
             Font-Name="Arial" Font-Size="10pt"
             HeaderStyle-Font-Bold="True"
             HeaderStyle-HorizontalAlign="Center"
             HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White"
             HeaderStyle-Font-Size="15pt"
             AlternatingItemStyle-BackColor="#eeeeee" 
                AllowPaging=false Font-Names="Arial" PageSize="3">
          <Columns>
            <asp:TemplateColumn HeaderStyle-BackColor="Gray" HeaderText="RSS FEED">
              <ItemTemplate>
                <a href="<%# DataBinder.Eval(Container.DataItem, "link")%>">
                  <%# DataBinder.Eval(Container.DataItem, "title") %></a><br />
                  <%# DataBinder.Eval(Container.DataItem, "description") %>
              </ItemTemplate>
            </asp:TemplateColumn>
          </Columns>
        </asp:DataGrid>        

    </div>
    </form>
</body>
</html>  

I've read several other articles that make this job more complicated than it needs to be, and now, with a few extra lines of code, your reader is customizable.

Points of Interest

One of the things I came across while researching this was a method to simply output the contents of an HTML page/XML page/RSS feed, by simply sending the URL:

/// <summary>
/// Reads XML from a given URL
/// </summary>
/// <param name="sourceFile"></param>
/// <returns></returns>
protected object getXML(string sourceFile)
{
    System.Net.WebRequest myRequest = System.Net.WebRequest.Create(sourceFile);
    System.Net.WebResponse myResponse = myRequest.GetResponse();
    System.Xml.XmlTextReader myReader = 
        new System.Xml.XmlTextReader(myResponse.GetResponseStream());
    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
    doc.Load(myReader);
    return (doc);
} 

History

  • 23rd October, 2007: Initial post

You can copy/paste the entire code listed above, or download the source file from the link at the top of this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

xbadenx

Systems Engineer

United States United States

Member

I have worked as a senior software engineer (C#) for over 10 years and currently serve as a technical architect for a global mobile software development company, guiding the development process for mobile applications for Android, BB, iPhone and iPad platforms.
 
I have worked for Nortel and IBM, and ran my own company which specializes in global mobile text messaging solutions.
 
Past tech flavors include C#, WCF, SOA, MVC, MVVM, Silverlight, Assembler, Pascal, VB, Java/J2EE/EJB/JDBC, Perl, TSQL, VisualAge, Websphere, TogetherSoft ControlCenter, Notes/Domino, and a whole lot of more capital letters put together that no one understands...

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralCompare Two XML Files Pinmembersavita_Bgm17:16 30 Dec '10  
GeneralProblem with live server PinmemberMember 31699811:18 25 Sep '09  
GeneralRe: Problem with live server Pinmemberxbadenx4:49 26 Nov '10  
GeneralThnaks it's really helpfull for me PinmemberMember 316998122:32 24 Sep '09  
GeneralNice Article PinmemberHemant.Kamalakar20:03 31 Oct '07  
GeneralWhere is the download PinmemberDewey12:50 23 Oct '07  
GeneralRe: Where is the download Pinmemberxbadenx12:58 23 Oct '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 23 Oct 2007
Article Copyright 2007 by xbadenx
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid