Bind an XMLDataSource to a GridView control

27 06 2007

On one of my ASP.NET 2.0 projects, I had to use an XML file as the data source for a GridView control. The problem was that I had never used this method before. But after doing some research, I found it to be very similar (and straightforward) to binding to a database – with the exception of the need to use XPath.

So…without further adieu, here are the steps and code. Enjoy!

1. Create an XML file that contains your data, like below (taken from Microsoft’s website to save a lot of typing). Save it as books.xml.

<?xml version="1.0"?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>
      An in-depth look at creating applications
      with XML.
    </description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
    <description>
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    </description>
  </book>
</catalog>

2. Add a GridView control to your .aspx page and rename it to gdvBooks.
3. Drag an XmlDataSource control to your form, rename it xdsBooks, and assign your XML file (books.xml) in the control’s DataFile property.
4. Next, change to Source view and input the code below.

<asp:GridView ID="gdvServerVersions" runat="server"         
    AutoGenerateColumns="False" DataKeyNames="id"         
    DataSourceID="xdsServerVersions" EmptyDataText="No data available.">                
    <Columns>
        <asp:BoundField HeaderText="Book ID" DataField="id" 
            SortExpression="id" />
        <asp:TemplateField HeaderText="Author">
            <ItemTemplate>
                <%# XPath("author") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Title">
            <ItemTemplate>
                <%# XPath("title") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Genre">
            <ItemTemplate>
                <%# XPath("genre") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Price">
            <ItemTemplate>
                <%# XPath("price") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Publish Date">
            <ItemTemplate>
                <%# XPath("publish_date") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Description">
            <ItemTemplate>
                <%# XPath("description")%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView> 

5. That’s it! Simply navigate to your newly created page and see the results.


				


Add text highlighting in ASP.NET 2.0 GridView

2 04 2007

I built an ASP.NET 2.0 web application [for the company I work for] that streamlined the deployment process to our production environment. It processed, tracked, archived, and notified automatically on each step of the deployment process.

So with that in mind, I’ll be showing you how to add text highlighting in a GridView; for example, a Date & Time column (i.e., red=overdue, green=still OK), which, at work, presented to the the technical group if a deployment was late or not. =0)

Here’s a screenshot:

Fig. 1.1 – Text highlighting in ASP.NET 2.0 GridView

Text highlighting in ASP.NET GridView

Adding this feature is quite easy. The first thing you’ll need to do is add a RowDataBound event in the GridView code:

<asp:GridView OnRowDataBound="GridView_RowDataBound">

The second thing is add an ASP label within an ASP template field, like so:

<asp:TemplateField HeaderText="Date & Time"

            SortExpression="TargetDateTime">

    <ItemTemplate>

        <asp:Label ID="lblTargetDateTime" runat="server"

                Text='<%# Eval("TargetDateTime") %>' />

    </ItemTemplate>

</asp:TemplateField>

Pretty simple so far, ‘ey?  Now, to the last bread-and-butter step, the code-behind file:

using System.Drawing;
private void GridView_RowDataBound(object sender,

        GridViewRowEventArgs e)

{

    // Find control to add text highlighting

    if (e.Row.RowType == DataControlRowType.DataRow)

    {

        // Create Label datatype then cast and assign control

        Label dateTimeType =

            (Label)e.Row.FindControl("lblTargetDateTime");


        // Instantiate new DateTime object

        DateTime dateTime = new DateTime();

        dateTime = Convert.ToDateTime(dateTimeType.Text);


        // Set coloring based on date and time

        if (DateTime.Compare(dateTime, DateTime.Today) >= 0)

            dateTimeType.BackColor = Color.LawnGreen;

        else

            dateTimeType.BackColor = Color.Red;

    }

}

That’s it! Using text highlighting in your GridView not only makes it look “pretty,” but also emphasizes a record’s importance based on colors.