matthew king

matthew king

  • NA
  • 52
  • 0

undbound datagrid

Mar 3 2010 11:32 AM

Experts,
I'm trying to determine how to export the contents (e.g. row/cells) of an unbound DataGrid to a text file via button_click event.  The datagrid contains a fixed number of columns (16).  Ultimately, I'm trying to have user click a button resulting in the exporting of rows to a .txt file (e.g. c:\test.txt).  So, if the datagrid has the following information:
Car           Engine            Doors        Color              Vin   
Ford          V6                    4              blue              454545454
Dodge       v4                    2              green           565686533
Honda       i4                     2              red               4545454545

It would create the follow test.txt:
Ford  V6 4 blue 454545454
Dodge v4 2 green 565686533
honda i4 2 red  4545454545

Unfortunately, I haven't gotten very far.  I'm able to read the contents of the cells into a string, but I can't determine how to write it to a text file.

        {
            StringBuilder sb = new StringBuilder();

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (!row.IsNewRow)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        sb.Append(" ");
                     
                      sb.Append(cell.Value.ToString());
  
                    }
                    // using (StreamWriter sw1 = new StreamWriter(@"C:\test.txt"))
 
                    MessageBox.Show(sb.ToString());
                   
                    {
                    }
                }
            }
        }
    }
}

Answers (4)