0

I am trying to make a simple WindowsForm application that includes about 35 text boxes whos data I want saved at the press of a button into a text file so that I can load the data back into the text boxes when the program starts up. I am having 3 major problems.

  1. figuring out the best way to write the information to a text file
  2. how to specify the path of the text file if it is in the application root directory
  3. how to read from the file at startup (I believe this would happen in Form1_Load)

Here is the code I have been fiddling with that hasn't worked at all. Each textbox should have it's own line in the text file that never changes.

    private void btnSaveCommands_Click(object sender, EventArgs e)
    {
        string path = System.IO.Path.GetDirectoryName("commands");
        var lines = File.ReadAllLines("commands.txt");
        lines[1] = commandTextBox1.Text;
        lines[2] = commandTextBox2.Text;
        lines[3] = commandTextBox3.Text;
        lines[4] = commandTextBox4.Text;
        lines[5] = commandTextBox5.Text;
        etc..... (35 times)
        File.WriteAllLines("commands.txt", lines);
    }

for loading the text I would do something like....

    private void Form1_Load(object sender, EventArgs e)
    {
    string path = System.IO.Path.GetDirectoryName("commands");
    var lines = File.ReadAllLines("commands.txt");
        commandTextBox1.Text = lines[1];
        commandTextBox2.Text = lines[2];
        etc....
    }

I'm not sure if a text file is even the best way to do this kind of thing so if there are any better or easier options please mention them.

I have done some more research and found that a registry might work?

Adam Nofsinger
  • 4,004
  • 3
  • 34
  • 42
Nate
  • 53
  • 2
  • 8
  • What's the issue with current solution? You can as well consider storing in DB. – Rahul Jun 15 '16 at 18:30
  • If this is being used for storing something like user preferences or static Application information I would use a Settings file. You can see how its used here, http://stackoverflow.com/questions/453161/best-practice-to-save-application-settings-in-a-windows-forms-application – Bearcat9425 Jun 15 '16 at 18:31
  • streamreader and streamwriter is the easiest way – Anonymous Duck Jun 15 '16 at 18:41
  • http://prntscr.com/bgsml7 I get this error when I try the program with the code above – Nate Jun 15 '16 at 18:43
  • IsolatedStoragefile would be what i would try http://stackoverflow.com/questions/12927718/winforms-c-store-retrieve-persist-content-of-textboxes-between-2-runs – Nikki9696 Jun 15 '16 at 18:44
  • so if I wanted to use the settings method like people have suggested what would I need to do In the properties for each object? – Nate Jun 15 '16 at 18:47

3 Answers3

1

Below is a small example which generates 10 textboxes at run-time, whose content can be saved to a file and reloaded afterwards. The only item that needs to be included inside the form at compile time is a button called saveButton. An important lesson you should learn in comparison to your implementation is to not repeat yourself, à la 35 separate lines to access the textbox. If you can loop it, do it.

    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        /// <summary>
        /// The collection of textboxes that need to be added to the form.
        /// </summary>
        private readonly IList<TextBox> inputBoxCollection;

        /// <summary>
        /// The name of the file to save the content to.
        /// </summary>
        private const string Filename = "textbox-text.txt";

        /// <summary>
        /// Initializes a new instance of the <see cref="Form1"/> class.
        /// </summary>
        public Form1()
        {
            this.InitializeComponent();
            this.inputBoxCollection = new List<TextBox>();
            for (var i = 0; i < 10; i++)
            {
                this.inputBoxCollection.Add(new TextBox { Location = new Point(0, i*25) });
            }
        }

        /// <summary>
        /// Handles the Load event of the Form1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void Form1_Load(object sender, EventArgs e)
        {
            var retrievedStrings = File.ReadAllLines(Filename);
            var index = 0;
            foreach (var textBox in this.inputBoxCollection)
            {
                if (index <= retrievedStrings.Length - 1)
                {
                    textBox.Text = retrievedStrings[index++];
                }

                this.Controls.Add(textBox);
            }
        }

        /// <summary>
        /// Handles the Click event of the saveButton control. When pressed, the
        /// content of all the textboxes are stored in a file called textbox-text.txt.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void saveButton_Click(object sender, EventArgs e)
        {
            var builder = new StringBuilder();
            foreach (var textBox in this.inputBoxCollection)
            {
                builder.AppendLine(textBox.Text);
            }

            File.WriteAllText(Filename, builder.ToString());
        }
    }
}

You also asked for better suggestions to saving content to a file. Databases and the registry were banded around, but for this sort of application, a simple text file on disk is ideal. Easily done and easy to maintain.

BlackBox
  • 2,223
  • 1
  • 21
  • 37
  • this text file would be in the application root dir right? – Nate Jun 15 '16 at 18:57
  • also how would I use existing text boxes instead of creating new ones when the form is loaded? – Nate Jun 15 '16 at 19:02
  • In this instance, the file would be created next to the .exe. So if you're in visual studio, you would find it within debug/release. You need to specify a path if you want it located in other places. – BlackBox Jun 15 '16 at 19:03
  • You could use @Luiso's answer to loop through existing controls – BlackBox Jun 15 '16 at 19:04
  • The DNRY concept: "You're not an artisan dude, stop doing so much manual work" – Felype Jun 15 '16 at 19:21
0

If your TextBoxes have a unique name, then you could do something like this:

public void SaveData(Form form)
{
    var data = form.Controlls
                   .OfType<TextBox>()
                   .ToDictionary(tb => tb.Name, tb => tb.Text);

    SaveToFile(data);
}

public void LoadData(Dictionary<string,string> data, Form form)
{
    var boxes = form.Controlls
                    .OfType<TextBox>()
                    .ToDictionary(tb => tb.Name);

    foreach(var kvp in data)
    {
        boxes[kvp.key].Text = kvp.Value;
    }
}

to do the SaveToFile you could easily use Newtonsoft.Json and to serialize the Dictionary<string, string> like this JsonConvert.SerializeObject(dict) and to get it back: JsonConvert.Deserialize<Dictionary<string,string>>(data) as for the file, you can save anywhere you want as long as you can read it back;

Luiso
  • 4,173
  • 2
  • 37
  • 60
0

You wrote

I'm not sure if a text file is even the best way to do this kind of thing so if there are any better/easier options plz mention them :)

There's nothing wrong with using the text file. However .Net provides an app.copnfig to store and persist application settings.

Right click on your project and goto the Settings tab. Add an entry for each setting you need. For example

Name             Type               Scope                Value
command1         string             User                 test1
command2         string             User                 test2
additional settings etc

in Form_Load

private void Form1_Load(object sender, EventArgs e)
{
    commandTextBox1.Text = Properties.Settings.Default.command1;
    commandTextBox2.Text = Properties.Settings.Default.command2;
    etc....
}

to Save

private void btnSaveCommands_Click(object sender, EventArgs e)
{
    Properties.Settings.Default.command1 = commandTextBox1.Text;
    Properties.Settings.Default.command2 = commandTextBox2.Text;
    etc..... (35 times)
    Properties.Settings.Default.Save();
}
user2880486
  • 1,068
  • 7
  • 16
  • well this was what I found to be the most simple answer with my experience programming and he explained how to setup settings and get/set their content very clearly. – Nate Jun 15 '16 at 19:30