[英]C# String not printed on sameline StreamWriter issue
我使用下面的代码通过将它们转换为字符串将datagrid视图中的整个内容打印到文本文件中! 数据网格视图有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);
}
}
}
}
尽管创建了一个文本文件,但前两列和第三列中的第一个字符串被打印在同一行上,而第三列中的其他字符串被打印在新行中! 我怎么能把他们放在同一条线上。
例如,让一个示例数据网格视图行像(aaa)(bbb)(ccc dddd eee),并且它必须在文本文件中显示为aaa bbb ccc dddd eee,但是从我的代码来看,它在同一行dddd上看起来像aaa bbb ccc在新的一行上,并在另一新的行上发布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();
}
}
除了依赖j==0
,您还可以在for循环的内部添加新行。 另外,要放入这么多字符串值,您应该真正使用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());
}
}
编辑:-似乎第三列包含带有换行符的字符串,因此我们可以在放入文件之前从字符串中删除换行符:
var s = val.ToString();
file.Append(s.Replace(Environment.NewLine, " "));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.