Tuesday, August 13, 2013

Binding GridView control to an XML data source



XML:
<books>
        <book>
            <title>CLR via C#</title>
            <isbn>0735667454</isbn>
            <author>Jeffrey Richter</author>
        </book>
        <book>
            <title>Pro C# 5.0 and the .NET 4.5 Framework</title>
            <isbn>1430242337</isbn>
            <author>Andrew Troelsen</author>
        </book>
        <book>
            <title>Building Windows 8 Apps with C# and XAML</title>
            <isbn>0321822161</isbn>
            <author>Jeremy Likness</author>
        </book>
    </books>

HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title>Book Store</title>
        </head>
        <body>
            <form id="form1" runat="server">
                <div>
                    <asp:GridView ID="gvBooks" runat="server">
                    </asp:GridView>
                </div>
            </form>
        </body>
    </html>

C# Code:
using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;

    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bindXml();
        }
        private void bindXml()
        {
            //Create a DataSet
            DataSet ds = new DataSet();
            //Load the XML data into the DataSet
            ds.ReadXml(Server.MapPath("books.xml"));

            //Bind the DataSet to the GridView control
            gvBooks.DataSource = ds;
            gvBooks.DataBind();
        }
    }

No comments:

Post a Comment