Towtow10 Towtow10 - 23 days ago 5
C# Question

Reading and writing tables from a list of labels in C#

How can I create a file containing a table created from a list of labels, E.g. if I had two labels above and below each other like this

foo
bar


They would be written into a table like this

Number Name

1----------foo

2----------bar

That table would then need to be written to a file.

Also how can I read the table from the file and create a list of labels on a panel.

Answer

Just write records into lines in a file.

var rows = panel.Controls.OfType<Label>().Select(t => t.Text);

File.WriteAllLines("file.txt", rows);

And read it line by line.

var rows = File.ReadAllLines("file.txt');

for (var i = 0; i < rows.Length; i++)
{
    var label = new Label
    {
        Text = rows[i],
        Top = i * 30
    };
    panel.Controls.Add(label);
}