Home > DeveloperSection > Forums > Saving Values In Xml And Retrieving Them
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    October-21-2014 12:25 AM

 XML XML  XAML 
Ratings:


 1 Reply(s)
 652  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. 


marcel ethan
marcel ethan

Total Post:105

Points:735
Posted on    October-21-2014 12:27 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick