Capstone B: the grid form

The CSV viewer is a grid with a filter, a sortable header and two file dialogs, and it is four files. The parser and the view model of the two lessons before are two of them; this lesson adds the form and the entry point, and builds all four together.

Four files

Viewer/ app.csproj nuget.config Program.cs the entry point CsvTable.cs the parser, the validator and the writer CsvViewModel.cs the BindingList, the filter and the sort CsvForm.cs the grid, the menus, the dialogs

The split follows the dependencies of the course: the table has no UI, the view model has no UI either, and the form has no parsing rule. The interface between the view model and the grid is BindingList<CsvRow>, which is the point of lesson 048 in a real application.

Program.cs

Three lines of composition: the default font and DPI from the generated initialiser, and the form. The store here is a file the user chooses, so there is nothing else to construct.

The file is Program.cs:

using System; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new CsvForm()); } }

CsvTable.cs

The parser, the validator and the writer of lesson 074, unchanged. The only thing the form needs beyond them is ToCsv, which is what the export writes.

The file is CsvTable.cs:

using System; using System.Collections.Generic; using System.Text; internal sealed class CsvTable { private CsvTable(List<string> header, List<List<string>> rows) { Header = header; Rows = rows; } public IReadOnlyList<string> Header { get; } public IReadOnlyList<List<string>> Rows { get; } public static CsvTable Parse(string text) { var rows = new List<List<string>>(); var row = new List<string>(); var field = new StringBuilder(); var quoted = false; var index = 0; if (text.Length > 0 && text[0] == '\uFEFF') { index = 1; } for (; index < text.Length; index++) { var c = text[index]; if (quoted) { if (c == '"' && index + 1 < text.Length && text[index + 1] == '"') { field.Append('"'); index++; } else if (c == '"') { quoted = false; } else { field.Append(c); } } else if (c == '"') { quoted = true; } else if (c == ',') { row.Add(field.ToString()); field.Clear(); } else if (c == '\n') { row.Add(field.ToString()); field.Clear(); rows.Add(row); row = new List<string>(); } else if (c != '\r') { field.Append(c); } } if (field.Length > 0 || row.Count > 0) { row.Add(field.ToString()); rows.Add(row); } var header = rows.Count > 0 ? rows[0] : new List<string>(); var body = rows.Count > 1 ? rows.GetRange(1, rows.Count - 1) : new List<List<string>>(); return new CsvTable(header, body); } public List<string> Validate() { var errors = new List<string>(); for (var i = 0; i < Rows.Count; i++) { var row = Rows[i]; var number = i + 1; if (row.Count != Header.Count) { errors.Add($"row {number}: expected {Header.Count} columns, found {row.Count}"); continue; } if (row[0].Trim().Length == 0) { errors.Add($"row {number}: id is empty"); } if (row[1].Trim().Length == 0) { errors.Add($"row {number}: name is empty"); } if (!decimal.TryParse(row[2], out var total)) { errors.Add($"row {number}: total is not a number"); } else if (total < 0m) { errors.Add($"row {number}: total must not be negative"); } } return errors; } public string ToCsv() { var builder = new StringBuilder(); AppendRow(builder, Header); foreach (var row in Rows) { AppendRow(builder, row); } return builder.ToString(); } private static void AppendRow(StringBuilder builder, IReadOnlyList<string> values) { for (var i = 0; i < values.Count; i++) { if (i > 0) { builder.Append(','); } builder.Append(Quote(values[i])); } builder.Append("\r\n"); } private static string Quote(string value) { if (value.IndexOfAny(new[] { ',', '"', '\n', '\r' }) < 0) { return value; } return "\"" + value.Replace("\"", "\"\"") + "\""; } }

CsvViewModel.cs

The view model of lesson 075. It keeps the source rows and rebuilds the visible BindingList on a filter or a sort. The grid binds to Visible and never sees the source list.

The file is CsvViewModel.cs:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; internal sealed record CsvRow(string Id, string Name, decimal Total); internal sealed class CsvViewModel : INotifyPropertyChanged { private readonly List<CsvRow> _rows = new(); private string _filter = string.Empty; private string _sortColumn = "Id"; private bool _sortAscending = true; public BindingList<CsvRow> Visible { get; } = new(); public int Count => Visible.Count; public int ErrorCount { get; private set; } public string Filter { get => _filter; set { if (_filter == value) { return; } _filter = value; OnPropertyChanged(); Refresh(); } } public string SortColumn => _sortColumn; public bool SortAscending => _sortAscending; public void Load(CsvTable table) { _rows.Clear(); foreach (var row in table.Rows) { if (row.Count == 3 && decimal.TryParse(row[2], out var total)) { _rows.Add(new CsvRow(row[0], row[1], total)); } } ErrorCount = table.Validate().Count; Refresh(); } public void SortBy(string column) { if (string.Equals(_sortColumn, column, StringComparison.Ordinal)) { _sortAscending = !_sortAscending; } else { _sortColumn = column; _sortAscending = true; } OnPropertyChanged(nameof(SortColumn)); OnPropertyChanged(nameof(SortAscending)); Refresh(); } public event PropertyChangedEventHandler? PropertyChanged; private void Refresh() { var matches = _rows.FindAll(Matches); matches.Sort(Compare); Visible.RaiseListChangedEvents = false; Visible.Clear(); foreach (var row in matches) { Visible.Add(row); } Visible.RaiseListChangedEvents = true; Visible.ResetBindings(); OnPropertyChanged(nameof(Count)); } private bool Matches(CsvRow row) => _filter.Length == 0 || row.Id.Contains(_filter, StringComparison.OrdinalIgnoreCase) || row.Name.Contains(_filter, StringComparison.OrdinalIgnoreCase); private int Compare(CsvRow left, CsvRow right) { var order = _sortColumn switch { "Name" => string.Compare(left.Name, right.Name, StringComparison.OrdinalIgnoreCase), "Total" => left.Total.CompareTo(right.Total), _ => string.Compare(left.Id, right.Id, StringComparison.OrdinalIgnoreCase), }; return _sortAscending ? order : -order; } private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }

CsvForm.cs

The form has four pieces. A menu with Open and Export, whose Export is disabled until a file is loaded. A tool strip with the filter box, bound to the view model's filter by one line. A read-only grid with three explicit columns, a right-aligned total, and SortMode = NotSortable so the header click goes to the view model. And a status strip that the view model's Count change updates.

The two dialogs write and read the whole file: File.ReadAllText into the parser, and File.WriteAllText of ToCsv. The export writes the table that was imported, not the filtered view, because a filter is a way of looking and not an edit.

The file is CsvForm.cs:

using System; using System.Drawing; using System.IO; using System.Windows.Forms; internal sealed class CsvForm : Form { private readonly CsvViewModel _vm = new(); private readonly DataGridView _grid = new(); private readonly ToolStripTextBox _filter = new() { Width = 200 }; private readonly ToolStripStatusLabel _status = new("Open a CSV file."); private readonly ToolStripMenuItem _export = new("&Export..."); private CsvTable? _table; public CsvForm() { Text = "CSV viewer"; ClientSize = new Size(640, 420); _export.Click += (sender, e) => Export(); var menu = new MenuStrip(); var file = new ToolStripMenuItem("&File"); file.DropDownItems.Add("&Open...", null, (sender, e) => Open()); file.DropDownItems.Add(_export); file.DropDownItems.Add(new ToolStripSeparator()); file.DropDownItems.Add("E&xit", null, (sender, e) => Close()); menu.Items.Add(file); MainMenuStrip = menu; var tools = new ToolStrip(); tools.Items.Add(new ToolStripLabel("Filter:")); tools.Items.Add(_filter); _filter.TextChanged += (sender, e) => _vm.Filter = _filter.Text; _grid.Dock = DockStyle.Fill; _grid.ReadOnly = true; _grid.AllowUserToAddRows = false; _grid.AllowUserToDeleteRows = false; _grid.AutoGenerateColumns = false; _grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; _grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect; _grid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "Id", DataPropertyName = "Id" }); _grid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "Name", DataPropertyName = "Name" }); _grid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "Total", DataPropertyName = "Total", DefaultCellStyle = new DataGridViewCellStyle { Format = "0.00", Alignment = DataGridViewContentAlignment.MiddleRight, }, }); foreach (DataGridViewColumn column in _grid.Columns) { column.SortMode = DataGridViewColumnSortMode.NotSortable; } _grid.DataSource = _vm.Visible; _grid.ColumnHeaderMouseClick += (sender, e) => _vm.SortBy(_grid.Columns[e.ColumnIndex].DataPropertyName); _grid.DataError += (sender, e) => e.ThrowException = false; var status = new StatusStrip(); status.Items.Add(_status); Controls.Add(_grid); Controls.Add(status); Controls.Add(tools); Controls.Add(menu); _export.Enabled = false; _vm.PropertyChanged += (sender, e) => { if (e.PropertyName == nameof(CsvViewModel.Count)) { UpdateStatus(); } }; } private void Open() { using var dialog = new OpenFileDialog { Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*", Title = "Open a CSV file", }; if (dialog.ShowDialog(this) != DialogResult.OK) { return; } try { _table = CsvTable.Parse(File.ReadAllText(dialog.FileName)); _vm.Load(_table); _export.Enabled = true; UpdateStatus(); } catch (IOException error) { _status.Text = error.Message; } } private void Export() { if (_table is null) { return; } using var dialog = new SaveFileDialog { Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*", Title = "Export the table", DefaultExt = "csv", AddExtension = true, }; if (dialog.ShowDialog(this) != DialogResult.OK) { return; } try { File.WriteAllText(dialog.FileName, _table.ToCsv()); _status.Text = $"Exported {_vm.Count} rows to {dialog.FileName}."; } catch (IOException error) { _status.Text = error.Message; } } private void UpdateStatus() => _status.Text = $"{_vm.Count} row(s), {_vm.ErrorCount} problem(s)."; }

The build

The four blocks above were extracted from this page as rendered, written into a folder with the project file and the feed, and built together:

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The build is real, and it is the whole viewer: four files, no missing member. The course checker builds one block at a time and reports Program.cs as skipped because the form is another file; the assembled build here is what proves the four files fit.

Nothing on this page starts the program: a grid needs Windows. What the run of lesson 075 proved is the part the grid displays, and what lesson 074 proved is the part the dialogs read and write. The form adds the columns, the filter box, the header click and the two dialogs.

Exercises

  1. Add a Rows column to the status strip that shows how many rows the file has and how many the filter hides.
  2. Add a CellFormatting handler that paints a negative total red, and say which layer decides that it is negative.
  3. Export only the visible rows and explain what the user loses and gains.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What are the four files?

    Answer

    Program, table, view model and form

    The parser and the view model are separate from the grid.

  2. What does the grid bind to?

    Answer

    The BindingList of visible rows

    The view model rebuilds it on a filter or sort.

  3. Why is SortMode NotSortable on every column?

    Answer

    The header click is handled by the view model instead

    A BindingList does not provide the grid sort.

  4. Which line connects the filter box to the view model?

    Answer

    The TextChanged handler that assigns vm.Filter

    One handler and one property.

  5. What does the export write?

    Answer

    The imported table, as CSV through ToCsv

    The filter is a view, not an edit.

  6. When is the Export menu enabled?

    Answer

    After a file is opened

    There is nothing to export before the first open.

  7. What does the view model Count change update?

    Answer

    The status strip

    The status text is the only listener.

  8. Where is the row count of the file kept?

    Answer

    In the view model, over all source rows

    The visible count and the source count differ under a filter.

  9. What would a cell formatting handler use to paint a negative total?

    Answer

    The decimal value of the row

    The value is a decimal, so the comparison is numeric.

  10. Why is Program.cs skipped by the course checker?

    Answer

    It references the form, which is in another file

    The page assembles the files and builds them together.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The four files of the viewer were assembled from this page and built together, as the build section says.

Article author: Arthur Isaev