How to write a text file from a .NET DataGridView control cell values?

无人久伴 提交于 2019-12-21 20:46:43

问题


I have the following code that should loop through all the rows in my DataGridView, and write all their cell values to a text file.
However, it outputs all the rows, but only the first cell of each one, and not the other three cells.

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

回答1:


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.
    }

Although, it would be cleaner if you used a foreach loop.




回答2:


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." );


来源:https://stackoverflow.com/questions/8457197/how-to-write-a-text-file-from-a-net-datagridview-control-cell-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!