Populate ListView from XML file
You need to add appropriate columns to the ListView
, and the fill the subitems for each item:
// Add required columns
listView1.Columns.Add("DMC");
listView1.Columns.Add("Tech Name");
listView1.Columns.Add("Info Name");
listView1.Columns.Add("Status");
listView1.Columns.Add("Notes");
XDocument doc = XDocument.Load(CSDBpath + projectName + "\\Data.xml");
foreach (var dm in doc.Descendants("dataModule"))
{
ListViewItem item = new ListViewItem( new string[]
{
dm.Element("DMC").Value,
dm.Element("techName").Value,
dm.Element("infoName").Value,
dm.Element("status").Value,
dm.Element("notes").Value
});
listView1.Items.Add(item);
}
Daedalus
I'm the director of a technical publications business writing documentation for aerospace. I'm desperately trying to learn C# as it will be extremely useful in my job to write programs that stremline our processes. Please be patient with me! :)
Updated on July 18, 2022Comments
-
Daedalus over 1 year
I have the following sample XML file from which i need to poplutate a ListView. I've been playing for hours but I don't know the best way to go about it. I want to use Linq to achieve this but my knowledge is somewhat lacking. It is a Winforms c# project.
<DMs> <dataModule> <DMC>11111</DMC> <techName>Test Techname 1</techName> <infoName>info 1</infoName> <status>complete</status> <notes>Note 1</notes> </dataModule> <dataModule> <DMC>22222</DMC> <techName>Test Techname 2</techName> <infoName>info 2</infoName> <status>in work</status> <notes>Note 2</notes> </dataModule> <dataModule> <DMC>33333</DMC> <techName>Test Techname 3</techName> <infoName>info 3</infoName> <status>QA required</status> <notes>Note 3</notes> </dataModule> </DMs>
I have the following very basic code which successfully populates the first column of the listview with the DMC element text, but i need the sibling elements (techName, infoname, status and notes) to populate the other columns of the listview.
XDocument doc = XDocument.Load(CSDBpath + projectName + "\\Data.xml"); var DMCs = from item in doc.Descendants("dataModule") select item.Element("DMC").Value; foreach (var dmc in DMCs) { ListViewItem item = new ListViewItem(dmc); listView1.Items.Add(item); }