Reputation: 365
I've created a windows form that takes user input and writes it to a text file in a comma separated manner and appends each new line. I want to be able to read all the data from that file and display it to the user on another windows form in either a rich text box or label.
The code below is what I have to read in the data to a specific location on my machine. I'm not sure if I first need to read the data into an array and then send that to a label or text box.
using (StreamWriter InputFile = File.AppendText(@"C:\Users\person\Desktop\C#\New Text Document.txt"))
{
InputFile.WriteLine(textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text);
MessageBox.Show("Data Saved!");
I know there are many other posts like this, but I can't seem to get the answer I'm looking for
Upvotes: 1
Views: 3477
Reputation: 112342
No, you could use File.ReadLines
, which returns an IEnumerable<string>
.
int i = 1;
foreach (string line in File.ReadLines(path)) {
string[] columns = line.Split(',');
for (int c = 0; c < columns.Length; c++) {
((TextBox)Controls["textBox" + i++]).Text = columns[c];
}
}
I assume that you have textboxes names textBox1
to textBox4
for the first line, textBox5
to textBox8
for the second line, and so on. But it would probably be better to use a grid.
Consider also using the TextFieldParser
in the namespace Microsoft.VisualBasic.FileIO
. It does all the CSV processing for you. You will have to add a reference to theMicrosoft.VisualBasic.dll
.
Note: the stuff in Microsoft.VisualBasic.dll is just a .NET library like any other and works as well in C# as in VB.
Upvotes: 1
Reputation: 13765
yes you have to read all lines in an array and using a code like the following
var lines =File.ReadAllLines(@"C:\Users\person\Desktop\C#\New Text Document.txt");
foreach (var line in lines)
{
var col = line.Split(',');
textBox1.Text = col[0];
textBox2.Text = col[1];
textBox3.Text = col[2];
textBox4.Text = col[3];
}
Upvotes: 1