Kushan Peiris Kushan Peiris - 2 months ago 17
C# Question

C# String not printed on sameline StreamWriter issue

The follwoing code is used by me to print entires in a datagrid view into text file by converting them into strings! The data grid view has 3 columns(3rd column has several strings) and I want to print each data grid view row as a single line in the text file!

private void button1_Click_1(object sender, EventArgs e) // converting data grid value to single string
{

String file = " " ;
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++)
{
if (dataGridView2.Rows[i].Cells[j].Value != null)
{
if (j == 0)
{
file = Environment.NewLine + file + dataGridView2.Rows[i].Cells[j].Value.ToString();
}
else
{
file = file + dataGridView2.Rows[i].Cells[j].Value.ToString();
}
}


}



using (StreamWriter sw = new StreamWriter(@"C:\Users\Desktop\VS\Tfiles\file.txt"))
{


{
sw.Write(file);
}
}

}
}


Though a textfile is created the first 2 columns and the 1st string in the 3rd column are printed on the same line but the other strings of the 3rd column are printed on a new line! how can i get them onto the same line.

eg- let a sample data grid view row be like (aaa) (bbb) (ccc dddd eee) and it must appear in the textfile as aaa bbb ccc dddd eee but from my code it appears like aaa bbb ccc on the sameline, dddd on a new line and eee on another new line! how can i correct this issue?

Answer Source

Instead of relying on j==0, you can append new line outside of inner for loop. Also to put in that many string values you should really use StringBuilder. Try this:

private void button1_Click_1(object sender, EventArgs e) // converting data grid value to single string
{

    StringBuilder file = new StringBuilder();
    for (int i = 0; i < dataGridView2.Rows.Count; i++)
    {
        for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++)
        {
            var val = dataGridView2.Rows[i].Cells[j].Value;
            if (val == null)
                continue;//IF NULL GO TO NEXT CELL, MAYBE YOU WANT TO PUT EMPTY SPACE
            var s=val.ToString();
            file.Append(s.Replace(Environment.NewLine," "));
        }
        file.AppendLine();//NEXT ROW WILL COME INTO NEXT LINE
    }

    using (StreamWriter sw = new 
                   StreamWriter(@"C:\Users\Desktop\VS\Tfiles\file.txt"))
    {
        sw.Write(file.ToString());
    }   
}

EDIT:- Seems 3rd column contains strings with new line so we can remove the new line from string before putting to file:

var s = val.ToString();
file.Append(s.Replace(Environment.NewLine, " "));