c# reading xml to listview

784 views Asked by At

Write XML code

XmlTextWriter xmlchat = new XmlTextWriter("chatroomdoc.xml", UTF8Encoding.UTF8);
        xmlchat.WriteStartDocument();
        xmlchat.Formatting = Formatting.Indented;
        xmlchat.WriteStartElement("Chat");
        foreach (ListViewItem one in lvmess.Items)
        {
            xmlchat.WriteStartElement("Client", one.SubItems[0].Text);
            xmlchat.WriteElementString("Nickname", one.SubItems[0].Text);
            xmlchat.WriteElementString("Message",one.SubItems[1].Text);
            xmlchat.WriteEndElement();
        }
        xmlchat.WriteEndElement();

        xmlchat.WriteEndDocument();
        xmlchat.Close();

This code is part of my client chat application it saves text messages into an xml file . I need to write a code that loads xml file to listview when you opened client.But i couldn't make read part right either lvmess.Items.Add fails because of while or when i do it outside while it works but only first items(obviously ) can anybody help me ?

This is Read File Code

    private void Form1_Load(object sender, EventArgs e){

        ListViewItem lis = new ListViewItem();
        using (XmlReader reader = XmlReader.Create("chatroomdoc.xml"))
        {
            int i =0;

            while (reader.Read())
            {

                    switch (reader.Name.ToString())
                    {
                        case "Nickname":
                            lis.Text=reader.ReadElementContentAsString();
                        break;
                        case "Message":
                            lis.SubItems.Add(reader.ReadElementContentAsString());

                        break;
                    }
                //lvmess.Items.Add(lis);
                //i++;

            }

            lvmess.Items.Add(lis);
        }
    }
1

There are 1 answers

1
Yuval Perelman On BEST ANSWER

you have created your ListViewItem outside of the while loop, and oon each iteration you just changed the data on the same ListViewItem. You should create a new item with each iteration and add it to your list so it could be used later. Something like this:

private void Form1_Load(object sender, EventArgs e){

    //ListViewItem lis = new ListViewItem();
    using (XmlReader reader = XmlReader.Create("chatroomdoc.xml"))
    {
        int i =0;

        while (reader.Read())
        {
                ListViewItem lis = new ListViewItem();
                switch (reader.Name.ToString())
                {
                    case "Nickname":
                        lis.Text=reader.ReadElementContentAsString();
                    break;
                    case "Message":
                        lis.SubItems.Add(reader.ReadElementContentAsString());

                    break;
                }
                lvmess.Items.Add(lis);
            //i++;

        }

       // lvmess.Items.Add(lis);
    }
}