Bharat Bharat - 3 years ago 125
ASP.NET (C#) Question

gridview with xml datasource

I am new to web forms.

I have XML, like below.

<row id="1" name="name1"/>
<row id="2" name="name2"/>
<row id="3" name="name3"/>
<row id="4" name="name3"/>
<row id="5" name="name3"/>

I want to bind this data to asp:GridView.
But only name part of xml not Id.

What I did is here, but it's not all.
I don't even know that it's proper or not.

protected void Page_Load(object sender, EventArgs e)
var XmlPath = Server.MapPath("~/Data.xml");
XmlDocument doc = new XmlDocument();

DataTable dt = new DataTable();
foreach (XmlNode xn in doc.ChildNodes[1])
string tagName = xn.Name;
if (!dt.Columns.Contains(tagName))

DataRow dr = dt.NewRow();
foreach (XmlNode xn in doc.ChildNodes[1])
dr[xn.Name] = xn.InnerText;


GridView1.DataSource = dt;

I also have to filter data, for exa. I want to print only those data whose ID is 2 and 4.

Answer Source

You can use LINQ to XML like this:

XDocument doc = XDocument.Load("~/Data.xml");

var names = from r in doc.Descendants("row")
             select (string)r.Attribute("name");

GridView1.DataSource = names;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download