简体   繁体   中英

C# - Save ListView contents as XML (With multicolumns) and read on Form_Load

My application has a ListView control that has data added to it across several columns and rows. When the form is closed (calling the Form_Closing event), the contents are saved to an XML file. Then, at the following run time, the XML document is read and its contents are displayed in the ListView control. For some reason, it only loads the first column and doesn't save all of the data. I am new to using XML to save data. Any and all help will be appreciated.

This is what I have so far, I'm sure there are plenty of errors:

    private void Form1_Load(object sender, EventArgs e)
    {
        System.Xml.XmlDocument loadDoc = new System.Xml.XmlDocument();
        loadDoc.Load(Application.StartupPath + "\\Accounts.xml");

        foreach (System.Xml.XmlNode emailNode in loadDoc.SelectNodes("/Accounts/Item"))
        {
            AccountList.Items.Add(emailNode.Attributes["email"].InnerText);;
        }

        foreach (System.Xml.XmlNode passwordNode in loadDoc.SelectNodes("/Accounts/Item"))
        {
            AccountList.Items.Add(passwordNode.Attributes["password"].InnerText); ;
        }

        foreach (System.Xml.XmlNode statusNode in loadDoc.SelectNodes("/Accounts/Item"))
        {
            AccountList.Items.Add(statusNode.Attributes["status"].InnerText); ;
        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Application.StartupPath + "\\Accounts.xml", null);

        writer.WriteStartElement("Accounts");
        for (int i =0; i < AccountList.Items.Count; i++)
        {
            writer.WriteStartElement("Item");
            writer.WriteAttributeString("email", AccountList.Items[i].Text);
            writer.WriteAttributeString("password", AccountList.Items[i].Text);
            writer.WriteAttributeString("status", AccountList.Items[i].Text);
            writer.WriteEndElement();
        }

        writer.WriteEndElement();
        writer.Close();
    }

Your first problem is that on FormClosing, you're writing out the same data:

        writer.WriteAttributeString("email", **AccountList.Items[i].Text**);
        writer.WriteAttributeString("password", **AccountList.Items[i].Text**);
        writer.WriteAttributeString("status", **AccountList.Items[i].Text**);

(Can't bold, sorry. Notice Items[i].Text is the same.)

You'll want to use something like AccountList.Items[i].SubItems[ 0 ].Text. Replace the 0 with 1, 2, etc for the column indexes. See http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.listviewsubitem.aspx for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM