How to Populate Data in the ListView Using XML File and C#

In this tutorial, I will teach you how to Populate Data in the ListView Using XML File and C#. This method has the ability to display the data from XML File to the ListView. This program is so simple and you can make it in no time. Please follow the instructions below to see how it works.

Creating XML FIle

Go to solution explorer and right click the file name. After that select “Add” and hit “New Item”. ps6 Choose the “XML File” and named it “XMLFile1” then click “Add”. ps5 Add data to the XML File.
  1. <NewDataSet>
  2. <person>
  3. <Name>Janno Palacios</Name>
  4. <Address>Kabankalan City</Address>
  5. </person>
  6. <person>
  7. <Name>Jeanniebe Palacios</Name>
  8. <Address>Kabankalan City</Address>
  9. </person>
  10. <person>
  11. <Name>Craig Palacios</Name>
  12. <Address>Kabankalan City</Address>
  13. </person>
  14. <person>
  15. <Name>Kenjie Palacios</Name>
  16. <Address>Kabankalan City</Address>
  17. </person>
  18. </NewDataSet>

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Add a ListView inside the Form just like shown below. ps2

Step 3

Put the XML File in the resources folder by dragging it. ps3

Step 4

Press F7 to open the code editor. In the code editor, create a method to get the data in the XML File and display it into the ListView.
  1.  
  2. private void LoadPerson(ListView lst)
  3. {
  4. DataSet dsCountries = new DataSet();
  5. dsCountries.ReadXml(new System.IO.StringReader(Properties.Resources.XMLFile1));
  6. lst.Columns.Add("Name");
  7. lst.Columns.Add("Address");
  8. lst.View = View.Details;
  9. lst.GridLines = true;
  10. lst.Items.Clear();
  11. for (int i = 0; i < dsCountries.Tables[0].Rows.Count; i++)
  12. {
  13. DataRow dr = dsCountries.Tables[0].Rows[i];
  14. ListViewItem listitem = new ListViewItem(dr["Name"].ToString());
  15. listitem.SubItems.Add(dr["Address"].ToString());
  16. lst.Items.Add(listitem);
  17. }
  18.  

Step 5

Write the following code to execute the method that you have created in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. LoadPerson(listView1);
  5. }
The complete source code is included. You can download it and run it on your computer. For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment