Monday, August 5, 2013
Labels:
Asp.net
,
Gridview
How to Read data from XML File and Bind to Gridview in asp.net with C# - Example
Posted by
Abhay Makadiya
at
8/05/2013
In previous article we have learned How to Import Data From Excel file to Database in Asp.net with C# - Example. an you can find other Gridview example here Gridview Here in this post we will discuss how to Read Data from XML file and bind it to grid view. It is very simple task you just have to create one DataSet object and call the method ReadXml() you have to pass one argument in it, which is file name from which you want to read data.
first of all i have one xml file Contact.xml it is as per following.
Here is the screen shot of my grid which is binded from XML file
first of all i have one xml file Contact.xml it is as per following.
<?xml version="1.0" encoding="utf-8" ?> <Contacts> <Contact> <Name>steve jobs</Name> <Number>0081663465</Number> <Address>USA</Address> </Contact> <Contact> <Name>Bill gates</Name> <Number>05601215</Number> <Address>US</Address> </Contact> <Contact> <Name>Peter Capaldi</Name> <Number>005642313</Number> <Address>USA</Address> </Contact> </Contacts>
Here is the screen shot of my grid which is binded from XML file
Source Code in Asp.net:-
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XMLtoGrid.aspx.cs" Inherits="BlogCodeTester.XMLtoGrid" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#41B7D8" Font-Bold="True" ForeColor="White" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> </asp:GridView> </div> </form> </body> </html>
Code in C#:-
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace BlogCodeTester { public partial class XMLtoGrid : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { readFromXML(); } private void readFromXML() { string myfile = @Server.MapPath("~/Contact.xml"); DataSet ds = new DataSet(); ds.ReadXml(myfile); if (ds.Tables[0].Rows.Count > 0) { GridView1.DataSource = ds; GridView1.DataBind(); } else { Response.Write("No data to display"); } } } }
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment