user826436
user826436

Reputation: 245

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

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

Upvotes: 3

Views: 17810

Answers (2)

mehdi
mehdi

Reputation: 1

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

Upvotes: 0

Chris Cudmore
Chris Cudmore

Reputation: 30151

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.

Upvotes: 5

Related Questions