如何从.NET DataGridView控件单元格值写入文本文件?

时间:2011-12-10 14:33:34

标签: c# for-loop datagridview streamwriter

我有以下代码应循环遍历DataGridView中的所有行,并将所有单元格值写入文本文件。
但是,它输出所有行,但只输出每个行的第一个单元格,而不是其他三个单元格。

string file_name = "C:\\test1.txt";

var objWriter = new System.IO.StreamWriter(file_name);

int count = dgv.Rows.Count;

for (int row = 0; row < count; row++)
{
    objWriter.WriteLine(dgv.Rows[row].Cells[0].Value.ToString());
}

objWriter.Close();

2 个答案:

答案 0 :(得分:5)

for (int row = 0; row < count; row++)
    {
        int colCount = dgv.Rows[row].Cells.Count; 
        for ( int col = 0; col < colCount; col++)  
        {
            objWriter.WriteLine(dgv.Rows[row].Cells[col].Value.ToString());

        }
        // record seperator could be written here.
    }

虽然如果你使用foreach循环会更干净。

答案 1 :(得分:0)

TextWriter sw = new StreamWriter(@"D:\\file11.txt");

        int rowcount = dataGridViewX1.Rows.Count;
        for (int i = 0; i < rowcount - 1; i++)
        {

            sw.WriteLine(dataGridViewX1.Rows[i].Cells[0].Value.ToString());
        }
        sw.Close();


        MessageBox.Show("Text file was created." );