Saving Values In Xml And Retrieving Them

Total Post:110


 1561  View(s)
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. Re: Saving Values In Xml And Retrieving Them

    Try this:

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

    // ....

        public partial class Form1 : Form
            public Form1()
                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.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.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.


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.