We need to have an XML file. Below is our XML. We will create a web application. Add this XML file in the solution.

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <STUDENTS>
  3. <STUDENT>
  4. <StudentID>1</StudentID>
  5. <Name>John Smith</Name>
  6. <Marks>200</Marks>
  7. </STUDENT>
  8. <STUDENT>
  9. <StudentID>2</StudentID>
  10. <Name>Mark Johnson</Name>
  11. <Marks>300</Marks>
  12. </STUDENT>
  13. <STUDENT>
  14. <StudentID>3</StudentID>
  15. <Name>Nitin Tyagi</Name>
  16. <Marks>400</Marks>
  17. </STUDENT>
  18. </STUDENTS>
Add a webpage. Write the following code in the .aspx file.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="BindGridviewFromXML.Index" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title></title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <asp:GridView ID="Grddata" runat="server" AutoGenerateColumns="false">
  11. <Columns>
  12. <asp:BoundFieldDataField="StudentId" HeaderText="StudentId" />
  13. <asp:BoundFieldDataField="Name" HeaderText="Name" />
  14. <asp:BoundFieldDataField="Marks" HeaderText="Marks" />
  15. </Columns>
  16. </asp:GridView>
  17. </div>
  18. </form>
  19. </body>
  20. </html>
Now we need to write some code to bind the gridview. Have a look at the code below.
  1. using System;
  2. usingSystem.Data;
  3. usingSystem.Web.UI;
  4. namespaceBindGridviewFromXML
  5. {
  6. public partial class Index: System.Web.UI.Page
  7. {
  8. protected void Page_Load(object sender, EventArgs e)
  9. {
  10. if (!Page.IsPostBack)
  11. {
  12. BindGridview();
  13. }
  14. }
  15. protected void BindGridview()
  16. {
  17. using(DataSet ds = new DataSet())
  18. {
  19. ds.ReadXml(Server.MapPath("~/Students.xml"));
  20. Grddata.DataSource = ds;
  21. Grddata.DataBind();
  22. }
  23. }
  24. }
  25. }
Let us run the application now and check the output.



Gridview is displaying the records that were present in the XML file.