-3

I have a streamreader and a streamwriter i've found from another solution here but I keep getting index out of bounds when I try to read what the streamwriter have written to my .txt file (from a datagridview)

Streamwriter:

StreamWriter sw = new StreamWriter("D:\\test.txt");
string line;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    line = "";
    foreach(DataGridViewCell cell in row.Cells)
    {
        line += cell.Value.ToString();
    }
    sw.WriteLine(line);
}
sw.Close();

Streamreader:

StreamReader sr = new StreamReader("D:\\test.txt");
string line;
string[] values;
int p = 0;

while (!sr.EndOfStream){

    line = sr.ReadLine();
    values = line.Split(',');
    for (int o = 0; o < values.Length; o++){

        dataGridView1[p, o].Value = values[o];
    }
    p++;

}
sr.Close();

my .txt file output (where the each number is written and placed into one cell, 4 cells total):

2345

edit (this works better for me):

 StreamReader sr = new StreamReader("D:\\test.txt");
            while (!sr.EndOfStream)
            {
                string[] rows = new string[3];
                rows = sr.ReadLine().Split(',');
                dataGridView1.Rows.Add(rows[0], rows[1], rows[2], rows[3]);
            }
sr.Close();
fins
  • 1
  • 1
  • Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Camilo Terevinto Apr 14 '18 at 13:55
  • 2
    The snippet forgets to add the row to make the indexing valid. – Hans Passant Apr 14 '18 at 14:26

2 Answers2

0

There are a couple possible issues I see.

  1. In the streamwriter, in the 2nd foreach try doing this :

    line += cell.Value.ToString() + ",";

It might be that the streamreader cannot find the , and doesn't split.

  1. You could try adjusting the streamreader like this :

        while (!sr.EndOfStream){
    
        line = sr.ReadLine();
        for (int o = 0; o < line.Length; o++){
    
            dataGridView1[p, o].Value = line[o];
        }
        p++;
    

Hopefully this might help, let me know.

0

This won't help you with Adding rows but this is a good reading code and also use StringBuilder.Append or StringBuilder.Append(String.Join(",", line)) and not string line +=

using (StreamReader sr = new StreamReader("file.txt"))
        {
            string line;

            while ((line = sr.ReadLine()) != null)
            {

            }
        }
Netanel
  • 68
  • 9