Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 791
Karthik Avatar asked Dec 10 '22 07:12

Karthik


2 Answers

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();
like image 116
Renatas M. Avatar answered Dec 29 '22 01:12

Renatas M.


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();
like image 35
Peyman Avatar answered Dec 29 '22 00:12

Peyman