Load XML data to GridView : XML GridView « XML « ASP.Net





Load XML data to GridView

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Grades" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Grades</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnViewGrades" runat="server" OnClick="btnViewGrades_Click" Text="View Grades" /><br />
        <asp:GridView ID="GridView1" runat="server"/>
        <asp:Label ID="lblResult" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Grades : System.Web.UI.Page
{
    protected void btnViewGrades_Click(object sender, EventArgs e)
    {

        Response.Write(WindowsIdentity.GetCurrent().Name + "<br>");

        WindowsImpersonationContext ctx = ((WindowsIdentity)User.Identity).Impersonate();

        Response.Write(WindowsIdentity.GetCurrent().Name + "<br>");

        try
        {
            DataSet ds = new DataSet();

            ds.ReadXml(Server.MapPath("Data.xml"));

            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }
        catch (UnauthorizedAccessException)
        {
            lblResult.Text = "Not Authorized!";
        }

        ctx.Undo();

        Response.Write(WindowsIdentity.GetCurrent().Name + "<br>");
    }
}

File: Data.xml

<?xml version="1.0" encoding="utf-8" ?>
<students>
  <student>
    <name>John Smith</name>
    <grade>B</grade>
  </student>
  <student>
    <name>Jane Doe</name>
    <grade>A</grade>
  </student>
</students>

 










Related examples in the same category

1.asp:GridView column alignment
2.Displaying XML Data in a GridView and a ListBox?