1

I want to write the grid values to each line of a text file.

The grid is as follows.

enter image description here

I want to write values of SensposX, SensPosY and SensPosZ with a white space tab in one line and like this it should follow for the remaining 12 rows.

May I know how to write this?

codec
  • 355
  • 1
  • 5
  • 18

1 Answers1

1

Option 1

To export a DataGridView to file, as a simple option you can use GetClipboardContent methos:

grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
grid.SelectAll();
var text = grid.GetClipboardContent().GetText();

Then you can simply use File.WriteAllText method to save contents to file:

System.IO.File.WriteAllText(filePath, text);

Note

  • You can select only columns or rows which you want to export. I used SelectAll() to export the whole grid.
  • You can have more control on exported text using this signature of GetText method.

Option 2

You can use linq to select cell values which you want and join them to create the text representation of DataGridView:

var lines = new List<string>();
var headers = grid.Columns.Cast<DataGridViewColumn>()
                            .Where(c => c.Visible).Select(c => c.HeaderText);
lines.Add(string.Join("\t", headers));
var rows = grid.Rows.Cast<DataGridViewRow>()
                        .Select(r => string.Join("\t", r.Cells.Cast<DataGridViewCell>()
                        .Where(c => c.Visible).Select(c => c.FormattedValue)));
lines.AddRange(rows);
var text = string.Join(Environment.NewLine, lines);
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398