Save Labels to a file and load information

Asked

Viewed 31 times

0

I’m trying to create a way to:

  1. create multiple Abels by one button - done;

  2. save the information of these Abels to a list (text, left coords and top coords) - done as shown below;

  3. load from this list in the text order, left, top to recreate the label in the same place after you have turned off the app - difficulty in this step;

The code I have for now is as follows::

List <String> labelList = new List<String>(); //lista para texto
List<int> labelLeft = new List<int>(); //coords left
List<int> labelTop = new List<int>(); //coords top

What I have for the write button in the file is as follows:

private void button3_Click(object sender, EventArgs e)
{
    foreach (Label label1 in this.Controls.OfType<Label>())
    {
        labelList.Add(label1.Text); //id da label é "label1"
        labelLeft.Add(label1.Left);
        labelTop.Add(label1.Top);
    }

    for (int i = 0; i < labelList.Count(); i++)
    {
        TextWriter tw = new StreamWriter("SavedGame.txt");

        // write lines of text to the file
        tw.WriteLine(labelList[i].Text);
        tw.WriteLine(labelLeft[i]);
        tw.WriteLine(labelTop[i]);

        // close the stream     
        tw.Close();
    }
}

The idea is to write the data into the file each time the cycle runs once so I have all the data on the first list.

Now my difficulty is reading the data to replay it because what I tried was the following:

private void button4_Click(object sender, EventArgs e)
{
    for (int i = 0; i < labelList.Count(); i++)
    {
        Label l = new Label();
        TextReader tr = new StreamReader("SavedGame.txt");

        string ltext = tr.ReadLine();
        string labelLeft = tr.ReadLine();
        string labelTop = tr.ReadLine();

        //Convert the strings to int
        l.Text = ltext;
        l.Left = Convert.ToInt32(labelLeft);
        l.Top = Convert.ToInt32(labelTop);

        // close the stream
        tr.Close();
    }
}

I know my reading script may be wrong but there is some way I can achieve the intended one I explained above?

Thank you.

  • What error occurred? You had exactly what difficulty?

  • 1

    the difficulty is in recreating the label that was saved through the data that is saved in the file. Currently the file is saving the text and position data. I cannot, after closing the program, use what is in the file to put the label on the screen again in the same position.

1 answer

1


I ran a simulation and found two problems:

  1. When saving, you are overwriting txt. use TextWriter tw = new StreamWriter("SavedGame.txt", true); to give append instead of overwriting the file.

  2. You are generating the label but not adding it to the form. Use this.Controls.Add(l); to add the Label l in the form.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.