ChrisCreateBoss
ChrisCreateBoss

Reputation: 323

Loading cell values in dataGridView from text file C#

I am using a StreamWriter to write all values on all exisiting cells in a dataGridView, that writer is working perfect. But my reader isn't doing its work very good.

This is my writer code(which has no problem):

 StreamWriter writer = new StreamWriter(valuePath);
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                writer.WriteLine(cell.Value);
            }
        }
        writer.Close();

This is my reader code:

StreamReader sr = new StreamReader(valuePath);
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                cell.Value = sr.ReadLine();
            }
        }
        sr.Close();

The output: Monday 1 Tuesday 2 Wednesday 3

This code is reading each line from the txt file into the "existing cells" in my dataGridView, so when the app is opened, there is only one row. That's why my reader is not working good. Can someone help me solve this??

Upvotes: 1

Views: 2836

Answers (1)

chouaib
chouaib

Reputation: 2817

I suggest that you write your text file in this format:

cell1, cell2, ...

cell1, cell2, ...

cell1, cell2, ...

...

to do that, change your writer code to :

StreamWriter writer = new StreamWriter(valuePath);
string line;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    line = "";
    foreach (DataGridViewCell cell in row.Cells)
    {
        line += cell.Value.ToString();
    }
    writer.WriteLine(line);
}
writer.Close();

The reader code should be changed accordingly to:

StreamReader sr = new StreamReader(valuePath);
string line;
string[] values;
int n=0;

while(!sr.EndOfStream)
{
    line = sr.ReadLine();
    values = line.Split(',');

    for(int m=0; m<values.Length; m++)
    {
       dataGridView1[m, n].Value = values[m];
    }
    n++;
}
sr.Close();

Upvotes: 1

Related Questions