using System; using System.Collections; using System.IO; using System.Text; using System.Windows.Forms; namespace FileSystemDatabase { class DataGridViewExporter { public string Delimiter { get; set; } public DataGridViewExporter() { } public void Save(DataGridView grid, string fileName) { if (File.Exists(fileName)) File.Delete(fileName); using (TextWriter writer = new StreamWriter(File.OpenWrite(fileName))) writer.Write(GetAll(grid)); } public string GetAll(DataGridView grid) { return GetString(grid.Rows, grid.Columns); } public string GetSelection(DataGridView grid) { if (grid.SelectedRows.Count > 0) return GetString(grid.SelectedRows, grid.Columns); if (grid.SelectedColumns.Count > 0) return GetString(grid.Rows, grid.SelectedColumns); if (grid.SelectedCells.Count > 0) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < grid.SelectedCells.Count; i++) { builder.Append(grid.SelectedCells[i].FormattedValue.ToString()); if (i < grid.SelectedCells.Count - 1) builder.Append(Delimiter); } return builder.ToString(); } return string.Empty; } private string GetString(IList rows, IList columns) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < columns.Count; i++) { builder.Append(((DataGridViewColumn)columns[i]).HeaderText); if (i < columns.Count - 1) builder.Append(Delimiter); } foreach (DataGridViewRow row in rows) { builder.AppendLine(""); for (int i = 0; i < columns.Count; i++) { builder.Append(row.Cells[i].FormattedValue.ToString()); if (i < columns.Count - 1) builder.Append(Delimiter); } } return builder.ToString(); } } }
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
10 PRINT "Don is cool" 20 GOTO 10