C# 字符串未打印在同一行 StreamWriter 问题上

C# String not printed on sameline StreamWriter issue

我使用以下代码将数据网格视图中的全部内容转换为字符串,从而将它们打印到文本文件中!数据网格视图有 3 列(第 3 列有几个字符串),我想在文本文件中将每个数据网格视图行打印为一行!

 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);
                    }
                }

            }
        }

虽然创建了一个文本文件,但前 2 列和第 3 列中的第一个字符串打印在同一行上,但第 3 列的其他字符串打印在新行上!我怎样才能让他们在同一条线上。

eg- 让样本数据网格视图行像 (aaa) (bbb) (ccc dddd eee) 并且它必须在文本文件中显示为 aaa bbb ccc dddd eee 但从我的代码来看它看起来像 aaa bbb ccc在同一条线上,dddd 换行,eee 换行!我该如何解决这个问题?

试试这个:

        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)
                {
                    file = file + dataGridView2.Rows[i].Cells[j].Value.ToString();
                }
            }

您可以在内部 for 循环之外追加新行,而不是依赖 j==0。另外,要放入那么多字符串值,您应该真正使用 StringBuilder。试试这个:

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());
    }   
}

编辑:- 似乎第 3 列包含带有换行符的字符串,因此我们可以在放入文件之前从字符串中删除换行符:

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