Binding Raw Xml to a DataGrid Control in ASP.Net
Xml has become a very ubiquitous and is an integral part of .Net and the System.Data namespace. The problem lies in that not many people know how to take advantage of some of the features. When we are using a database, we naturally use the Systen.Data namespace, but with Xml documents as data there are hundreds of solutions for displaying Xml data out there for .Net.
I myself prefer to use the DataSet object and the DataGrid control just as I would if the data was coming from SQL Server. The common misconception, even to those who know that you can do this, is that you need a schema to accomplish it. There is a very simple way to bind raw Xml data to a datagrid without a schema. The Xml data must be simple though, mapping to rows easily.
For the example I used the following Xml data which is the result of a ForXml query against the pubs database.
<root>
<Titles>
<Title>The Busy Executive's Database Guide</Title>
<Type>business </Type>
<Price>19.9900</Price>
</Titles>
<Titles>
<Title>Cooking with Computers: Surreptitious Balance Sheets</Title>
<Type>business </Type>
<Price>11.9500</Price>
</Titles>
</root>
Next I created a web form with a DataGrid on it. Using the property builder for the DataGrid, I set up the styles for the header and the items. After this I added the following code to the Page_Load event:
ds.ReadXml(Server.MapPath("titles.xml"),XmlReadMode.InferSchema);
> this.DataGrid1.DataSource = ds;
this.DataGrid1.DataBind();
As you can see, it only takes four lines of code to bind the Xml data to the DataGrid. First you create a new DataSet object. Next you use the ReadXml method of the DataSet object. If you have a schema, the second argument is not needed, but you must also call the ReadXmlSchema like this (It will validate as well and throw an error if the data does not match the schema and you must load the schema first):
Without a schema, you must specify the second argument as above so that the schema (although very base and unuseful) is inferred from the structure of the Xml data. The result of the code looks like this:

If you want to get the Xml data from a database ForXml query or command, you can use the following implementation:
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog= pubs;UserId=sa;Password=SQLPassword;");
conn.Open();
SqlCommand cmd = new SqlCommand("Select top 2 * from Titles for xml auto",conn);
XmlReader xr = cmd.ExecuteXmlReader();
DataSet ds2 = new DataSet();
ds2.ReadXml(xr,XmlReadMode.InferSchema);
this.DataGrid2.DataSource = ds;
this.DataGrid2.DataBind();
With the Xml data in a datagrid you can sort, page and all sorts of other neat stuff. And as you can see, it is very easy to use. Also, if the data source ever changes, like from Xml to a stored procedure, then changing the code is very easy. Well that is it!!! Happy Coding!!!




20. Oct, 2006 by 







No comments yet... Be the first to leave a reply!