Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Wednesday, 4 February 2015

 

Introduction:   In this article we will learn how to bind XML file data to GridView after sorting in asp.net using Dataset.
Implementation: Let's create an asp.net application to understand.

First Create a new website and add XML file. To add XML file follow the simple steps:
Go to Website Menu -> Add New Item -> Select XML File and give name “books.xml”. Then paste the following xml tags in the books.xml file


<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book>
    <Title>Two States</Title>   
    <Author>Chetan Bhagat </Author>
    <Price>150</Price>
  </Book>

  
  <Book>
    <Title>Half Girlfriend</Title>   
    <Author>Chetan Bhagat </Author>
    <Price>120</Price>
  </Book>

  <Book>
  <Title>Revolution 2020</Title>   
    <Author>Chetan Bhagat </Author>
    <Price>180</Price>
  </Book>
   
</Books>
  • Place a GridView control on design page (.aspx)
<asp:GridView ID="grdBooks" runat="server">
</asp:GridView>

C#.Net Code  to sort DataSet and bind XML file data to GridView in asp.net

  • In the code behind file(.aspx.cs) write the code as:
    protected void Page_Load(object sender, EventArgs e)
    {
        readFromXMLShowInGrid();
    }
    private void readFromXMLShowInGrid()
    {
        string myfile = @Server.MapPath("books.xml");
        DataSet ds = new DataSet();
        ds.ReadXml(myfile);
        //Sort by Title of the book
        DataView dv = new DataView(ds.Tables[0]);
        dv.Sort = "Title";

        if (ds.Tables[0].Rows.Count > 0)
        {
            grdBooks.DataSource = dv;
            grdBooks.DataBind();
        }
        else
        {
            Response.Write("No data to display");
        }      
    }

VB.Net Code  to sort DataSet and bind XML file data to GridView in asp.net
  • In the code behind file(.aspx.vb) write the code as:

Protected Sub Page_Load(sender As Object, e As EventArgs)
        readFromXMLShowInGrid()
End Sub


Private Sub readFromXMLShowInGrid()
        Dim myfile As String = Server.MapPath("books.xml")
        Dim ds As New DataSet()
        ds.ReadXml(myfile)
        'Sort by Title of the book
        Dim dv As New DataView(ds.Tables(0))
        dv.Sort = "Title"

        If ds.Tables(0).Rows.Count > 0 Then
               grdBooks.DataSource = dv
               grdBooks.DataBind()
        Else
               Response.Write("No data to display")
        End If
End Sub


Categories: , ,

0 comments:

Post a Comment