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

17,617
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.

Share:
17,617
user826436
Author by

user826436

Updated on June 04, 2022

Comments

  • user826436
    user826436 about 2 years

    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();
    
    • David Hall
      David Hall over 12 years
      Chris' answer is correct - you need to loop over the cells as well as the rows. One suggestion I'd make though is to use a foreach on the rows and cells collection - this will tidy the code a little and save needing to get the row from the rows collection for each column lookup.
  • dgilperez
    dgilperez over 9 years
    Welcome to Stackoverflow! Can you elaborate?