Manually Bind XML Data to GridView in Asp.Net

Leave a Comment

In this article, We study how to manually bind XML Data to Gridview in Asp.Net.

Create XML file (books.xml)

<?xml version="1.0" encoding="utf-8" ?>
<Root>
  <Book>
    <BookID>1</BookID>
    <Title>Access Book</Title>
    <ISBN>0-596-00084-7</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>2</BookID>
    <Title>ASP.NET Book</Title>
    <ISBN>0-596-00378-1</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>3</BookID>
    <Title>Perl Book</Title>
    <ISBN>1-565-92243-3</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>4</BookID>
    <Title>Java Book</Title>
    <ISBN>0-596-00170-3</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>5</BookID>
    <Title>JavaScript Application Book</Title>
    <ISBN>1-565-92577-7</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>6</BookID>
    <Title>VB .Net Language in a Nutshell</Title>
    <ISBN>0-596-00092-8</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>7</BookID>
    <Title>Programming Visual Basic .Net</Title>
    <ISBN>0-596-00093-6</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>8</BookID>
    <Title>Programming C#</Title>
    <ISBN>0-596-00117-7</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>9</BookID>
    <Title>.Net Framework Essentials</Title>
    <ISBN>0-596-00165-7</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
  <Book>
    <BookID>10</BookID>
    <Title>COM and .Net Component Services</Title>
    <ISBN>0-596-00103-7</ISBN>
    <Publisher>Technical</Publisher>
  </Book>
</Root>

Now, add Gridview to Default.aspx page as follow-
<asp:GridView ID="GridView1" runat="server">
     <Columns>
<asp:BoundField HeaderText="Title"
DataField="Title" />
<asp:BoundField HeaderText="ISBN"
DataField="ISBN"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Publisher"
DataField="Publisher"
ItemStyle-HorizontalAlign="Center" />
</Columns>
    </asp:GridView>

Now, Use below code to Bind the XML data manually to Gridview in Code behind page(Default.aspx.cs).
protected void Page_Load(object sender, EventArgs e)
    {
        const String BOOK_TABLE = "Book";
        DataSet dSet = null;
        String xmlFilename;
        if (!Page.IsPostBack)
        {
            xmlFilename = Server.MapPath("~") + "\\books.xml";
            dSet = new DataSet();
            dSet.ReadXml(xmlFilename);
            GridView1.DataSource = dSet.Tables[BOOK_TABLE];
            GridView1.DataBind();
        }
    }

Demo


0 comments:

Post a Comment