SAVING VALUES IN XML AND RETRIEVING THEM

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
XML  XAML 
XML
 949  View(s)
Ratings:
Rate this:
i have a 4 to 5 textboxes and 2buttons to save and retrieve the values back, after clicking on save button all the textbox values should be saved in xml file,and when i click on retrieve button the values from xml file should be retrieved in listbox or listview. 
  1. marcel ethan

    Post:105

    Points:735
    Re: Saving Values In Xml And Retrieving Them

    Try this:

    using System.Xml;
    using System.Xml.Linq;

    // ....

        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                btnRetrieve.Enabled = false;
            }

            private string filePath = @"c:\myfiles\whatever.xml";

            private void btnSave_Click(object sender, EventArgs e)
            {           
                XElement textBoxes = new XElement("textboxes");

                // assumes all textboxes placed directly on form
                int count = this.Controls.Count;
                for(int i = count - 1; i >= 0; i--)
                {
                    Control c = this.Controls[i];

                    if (c is TextBox)
                    {
                        XElement textBox = new XElement("textbox");
                        textBox.Add(new XAttribute("name", c.Name));
                        textBox.Value = c.Text;
                        textBoxes.Add(textBox);
                    }
                }

                textBoxes.Save (filePath);
                btnRetrieve.Enabled = true;
            }

            private void btnRetrieve_Click(object sender, EventArgs e)
            {
                XElement textBoxes = XElement.Load(filePath);
                foreach (XElement textBox in textBoxes.Elements("textbox"))
                {
                    listBox1.Items.Add(textBox.Value);
                }
                listBox1.SelectedIndex = 0;
            }
        }


    If you're wondering why I'm iterating backwards through the controls collection to retrieve the textbox values, that's because (for some unknown reason) the VS designer adds them to the collection in the reverse order they were added to the form.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!