在C#窗体中从DataGridView写入文本文件 [英] Writing to a text file from DataGridView in C# windows form

查看:157
本文介绍了在C#窗体中从DataGridView写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据从我的 DataGridView 写入一个文本文件。

I want to write the data from my DataGridView to a textfile.

以下代码写入数据,但格式不正确。

The following code writes the data but it is not formatted correctly.

StreamWriter sW = new StreamWriter(dirLocationString);

string lines = "";

for (int row = 0; row< numRows1; row++){
     for (int col = 0; col < 4; col++)
         {

          lines = lines + " " + dataGridView1.Rows[row].Cells[col].Value.ToString();

         }

      sW.WriteLine(lines);
}

   sW.Close();   

我希望输出格式如下:

AAAA, BBBB, CCCC, DDDD 

它显示以下内容:

AAAA BBBB CCCC DDDD
AAAA BBBB CCCC DDDD AAAA BBBB CCCC DDDD
AAAA BBBB CCCC DDDD AAAA BBBB CCCC DDDD AAAA BBBB CCCC DDDD
and so on..


推荐答案

Init lines in first loop:

Init lines in first loop :

StreamWriter sW = new StreamWriter(dirLocationString);

for (int row = 0; row< numRows1; row++){
    string lines = "";
    for (int col = 0; col < 4; col++)
    {
        lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView1.Rows[row].Cells[col].Value.ToString();
    }

    sW.WriteLine(lines);
}

sW.Close(); 

这篇关于在C#窗体中从DataGridView写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆