Karthik
Karthik

Reputation: 318

Any way to populate items from xml to Datagridview using c#

I'm working on the datagridview. In which i have to show the values of the column from the xml to the grid view column. I have xml like this:- Also i have a grid view which have two column "ID" and "NAME",I want to populate the values from the xml to grid view .Can anyone help?

<employee>
    <empdetails id="1" name="sam"/>
    <empdetails id="2" name="robin"/>
    <empdetails id="3" name="victor"/>
</employee>

Upvotes: 4

Views: 18820

Answers (2)

Peyman
Peyman

Reputation: 3138

You can use XML Linq as below

XElement xml = XElement.Load(XMl String);
var xmlData = from item in xml.Element("empdetails")                              
                          select new {id = item.Attribute("id") , name= item.Attribute("name")};
dataGrid.DataSource = xmlData.ToList();

Upvotes: 3

Renatas M.
Renatas M.

Reputation: 11820

You can read xml to DataSet and pass DataSet empdetails table to DataGridView like this:

//Create xml reader
XmlReader xmlFile = XmlReader.Create("fullPathToYourXmlFile.xml", new XmlReaderSettings());
DataSet dataSet = new DataSet();
//Read xml to dataset
dataSet.ReadXml(xmlFile);
//Pass empdetails table to datagridview datasource
dataGridView.DataSource = dataSet.Tables["empdetails"];
//Close xml reader
xmlFile.Close();

Upvotes: 12

Related Questions