Click here to Skip to main content
14,932,270 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to make a Windows program in C# that has a load and save button the save button will save every textbox in the program to a xml file, and the load button will load the xml and populate each textbox with the corresponding text or number.

Any ideas please comment if you can with step by step, I will greatly appreciate your feedback.

What I have tried:

I've tried a few things found on youtube but was only able to save but that didn't really work.
Updated 2-May-21 13:30pm
BillWoodruff 2-May-21 7:57am
Are there always the same number of TextBoxes, or are they added/deleted during game play ?

Do you need to save/load only the TextBox Text ... that's easy ... or, do you need to save both Text and visual state ... that's harder ?
Aurora51x 2-May-21 15:28pm
Always be the same number of textboxes, and just trying to save whatever the user types in each of the textboxes to a xml and can be loaded back in each textboxes.

Either textboxes or Comboboxes
Save whatever the user selected in each combo box tons xml and load the xml to load there options they selected from exch comboboxes.
BillWoodruff 3-May-21 20:01pm
see the solution I added

You can use Xelement.Load and Xelement.Save, see examples here:
XElement.Load Method (System.Xml.Linq) | Microsoft Docs[^]

XElement xmlTree1 = new XElement("Root",  
    new XElement("Child", "content")  

XElement xmlTree2 = XElement.Load("Tree.xml");  

Another idea might be to use serialization, see: Lesson 10 - Serialization and deserialization in C# .NET[^]
Aurora51x 2-May-21 2:30am
I'll give this a look into tomorrow I'll keep the forum updated!
BillWoodruff 3-May-21 20:02pm
Once you learn how to use a DataContractSerializer, I predict you'll use it frequently.

Keep in mind that WinForm Control instances will not serialize directly; however, you can save most Properties of most of the Controls. For example, you can save Properties of the 'Font, like Font.Name, etc.

All WinForm Controls inherit from 'Control: so, for any Control, Properties like 'Name, 'Text can be accessed. A specific Control may have Properties it does not inherit from Control: for example, a TextBox has a BorderStyle Property; cast it into 'Control, and that property is not exposed.

So, the strategy is to save the Properties of Controls that you can use, then, restore the state of those Properties as needed to restore the Control/
// Required:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Windows.Forms;

namespace YourNameSpace

    /* This simple Class holds the values of the Name and Text Properties of a Control. [DataContract] marks the Class as Serializable, Deserializable. [DataMember] marks a Property of the Class as Serializable, Deserializable.
    public class ControlNameText
        public ControlNameText(Control cntrl)
            Name = cntrl.Name;
            Text = cntrl.Text;

        public string Name { set;  get; }
        public string Text { set;  get; }
    // we want to save a collection of ControlNameText:
    public static class ControlsSaveLoad
        private static string baseFolderPath = @"C:\Users\test_user\Desktop\Test\test.xml";

        private static DataContractSerializer dcs = new DataContractSerializer(typeof(List<ControlNameText>));

        [DataMember] public static List<ControlNameText> Cntrls = new List<ControlNameText>();

        public static void Save(Form frm)
            foreach (Control cntrl in frm.Controls.OfType<TextBox>())
                Cntrls.Add(new ControlNameText(cntrl));

            using (var writer =
                new FileStream(baseFolderPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                dcs.WriteObject(writer, Cntrls);

        public static void Load(Form frm)
            using (var reader = new FileStream(baseFolderPath, FileMode.Open, FileAccess.Read))
                Cntrls = (List<ControlNameText>) dcs.ReadObject(reader);

            foreach (ControlNameText cntrl in Cntrls)
                frm.Controls[cntrl.Name].Text = cntrl.Text;
Use example:
private void Form1_Load(object sender, EventArgs e)
I suggest you study this example carefully; saving the ComboBoxes 'SelectedText Property can be implemented the same way. I expect you to implement this example and research each step of the solution.


0) this code omits the error trapping/handling necessary for real-world use: you should implement checking for FileNotFoundError, etc.

1) the search for TextBoxes only gets the ones in the top-Level Form.ControlCollection.

2) I will not explain. or extend, this code further; however, I will answer questions from you that show you have studied this solution, run it, and done research on how it works.
That's a very strange request, and it's unlikely to be successful without a lot of thinking about.

The problems are two fold: firstly, very few programs (in the real world at least) have only one form, and many, many of them have multiple instances of some forms - so "saving and restoring them" means both recognising the actual form the textbox is on and regenerating that form when your restore the data along with all the other data that makes it distinct (and usable) as part of your total application. It's not normal for all that information to be available as textboxes!

Secondly, textboxes are a trivial part of an application, they only hold data that is suitable and necessary for the user to see - they don't contain thinks like GUID ID's which link the data back to a specific row in a DB for example.

While it's possible - and even relatively trivial - to get the content from "every textbox in an application" it's nowhere near as simple as you seem to think to save it ion a form that allows you to accurately restore it to the right place, you need to store "metainformation" with the box that identifies the textbox it came from to make sure that you restore it back to it's original place.

All in all, it's a mess - and that leads us to the next, biggest problem with the whole idea: it's going to fail dramatically when you upgrade or just change your application!

Stroeing yoru textbox content blindly like this "ties" your data to your application current design - is become pretty difficult to alter your app without having to think long and hard about any possible effects on the data before you do - a simple change like requiring a first name and last name separately instead of a single "name" textbox could give you hours of fun fixing data files!

Overall, I'd say your aren't thinking properly about how to do this: I'd design a data file format and then work out where to get the information from when I save it, and where it goes when I load it. To that end, I'd probably create a class or classes which can be serialized to XML or JSON, or whatever which I create instance(s) for when I want to save, and use as a data source when I want to load.
Blindly using textboxes may seem like a simple route to doing this, but it's honestly fraught with major trouble in the future!
Aurora51x 2-May-21 2:15am
Do you have any solution with steps to learn from.

The application will be for a game to remember gun attachments and the user can type there attachment names in the text boxes and save it to a file on there computer and then if application is closed they can simply click the load button and click the file and load the attachments back into the corresponding textboxes
OriginalGriff 2-May-21 8:57am
Right - so to heck with the text boxes!
What you should be looking at is a ship (or whatever) class that "knows" where it's guns can be mounted, and which holds which type of weapon is mounted in which emplacement.
Then serialize the ship class instance and it saves the emplacements ready fro when you restore.

Sounds complex? It isn't - it's actually easier than your method because you don't have to use the textboxes at all except when the user is changing things about.
And in future when the text base system is replaced with a graphic "drag'n'drop" system like most games use only the UI code needs to change - the remainder of your code uses the ship class instance which hasn't changed at all!

Does that make sense?
Aurora51x 2-May-21 2:31am
Thank you I'll look into my thought process tho. I appreciate your response and future responses
BillWoodruff 2-May-21 8:00am
I think the OP just wants to save/load the Text in each TextBox ... that is not difficult.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900