Capstone B: the view model
A DataGridView bound to a List<T> shows the list once and never again: the list has no way to say that it changed. The type that does say it is BindingList<T>, and lesson 048 introduced it. This lesson puts one behind a filter and a sort, and runs the whole view model with no grid.
A BindingList over the rows
The view model keeps two collections. The private list is every row of the file, in the order the file had. The public BindingList<CsvRow> is the rows that pass the current filter and sort, and it is what the grid binds to. Rebuilding the public list on a filter is cheap for a file of a few thousand rows, and it avoids the change-tracking a live filtered view would need.
The row itself is a record: CsvRow(string Id, string Name, decimal Total). The grid binds to its properties by name, and the record gives them exactly once. The view model reads the strings of the parsed table and skips a row whose total does not parse, which is also a row the validator reports.
Filtering
The filter is a case-insensitive substring over the id and the name. It is not a query language, and it should not become one: the user types ada and sees the rows that mention Ada. A filter that matched only the name would not find a row by its id, which is what a support person usually has.
The setter returns early when the text did not change, raises PropertyChanged for the filter, and rebuilds the visible list. The early return matters when the filter box raises an event per keystroke: the last keystroke of a duplicate is not a new filter.
Sorting by a column
A grid column can be sortable by itself only over a data source that implements sorting. A BindingList<T> does not, so the form sets SortMode = NotSortable on every column and handles ColumnHeaderMouseClick by calling the view model. That is a small amount of code and it gives the sort a direction per column, which the default grid sort does not.
SortBy names a column and toggles the direction when the same column is named twice. It then sorts the filtered copy, not the source list, so the order in the file is preserved for the next filter. The comparison is a switch over the three columns: a string comparison for the id and the name, and decimal.CompareTo for the total, which is numeric and not lexicographic.
What the grid listens to
Four notifications make the screen follow the model. Visible.ResetBindings() tells the bound grid that the whole list changed, which is what a filter does. The ListChanged events of the list tell the grid about a row. PropertyChanged(nameof(Count)) tells the status strip how many rows are visible. And SortColumn and SortAscending are there for a header that shows an arrow.
The view model raises a Count change after every rebuild, which is once per filter and twice per sort toggle. The status line therefore follows the filter without the form recomputing anything, and the form still has no rule of its own.
The view model in a program that runs
Five rows, one of them invalid, driven through the filter and both sort directions. The program prints every property change it raises, so the output is also the list of what a grid would receive. It was built and run in the container:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
Console.WriteLine("a CSV view model over five rows");
var table = CsvTable.Parse("id,name,total\nA-2,Grace Hopper,340.50\nA-1,Ada Lovelace,1250.00\nA-4,Alan Turing,10.00\nA-3,Grace Hopper,900.00\nA-5,Bad Row,-1\n");
var vm = new CsvViewModel();
vm.PropertyChanged += (sender, e) => Console.WriteLine($"changed: {e.PropertyName}");
vm.Load(table);
Console.WriteLine($"rows: {vm.Count}, errors: {vm.ErrorCount}");
Print("all", vm);
vm.Filter = "ada";
Print("filter 'ada'", vm);
vm.Filter = "a";
Print("filter 'a'", vm);
vm.Filter = string.Empty;
vm.SortBy("Total");
Console.WriteLine($"sorted by total up: {string.Join(", ", vm.Visible.Select(row => row.Total))}");
vm.SortBy("Total");
Console.WriteLine($"sorted by total down: {string.Join(", ", vm.Visible.Select(row => row.Total))}");
void Print(string label, CsvViewModel model)
{
Console.WriteLine($"{label}: {model.Count}");
foreach (var row in model.Visible)
{
Console.WriteLine($" {row.Id} {row.Name} {row.Total:0.00}");
}
}
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));
}
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 System.Text.StringBuilder();
var quoted = false;
foreach (var c in text)
{
if (quoted)
{
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' && c != '\uFEFF')
{
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;
}
}
dotnet run
a CSV view model over five rows
changed: Count
rows: 5, errors: 1
all: 5
A-1 Ada Lovelace 1250.00
A-2 Grace Hopper 340.50
A-3 Grace Hopper 900.00
A-4 Alan Turing 10.00
A-5 Bad Row -1.00
changed: Filter
changed: Count
filter 'ada': 1
A-1 Ada Lovelace 1250.00
changed: Filter
changed: Count
filter 'a': 5
A-1 Ada Lovelace 1250.00
A-2 Grace Hopper 340.50
A-3 Grace Hopper 900.00
A-4 Alan Turing 10.00
A-5 Bad Row -1.00
changed: Filter
changed: Count
changed: SortColumn
changed: SortAscending
changed: Count
sorted by total up: -1, 10.00, 340.50, 900.00, 1250.00
changed: SortColumn
changed: SortAscending
changed: Count
sorted by total down: 1250.00, 900.00, 340.50, 10.00, -1
The output is the real run. The load raised one Count change. Each filter raised Filter and Count, in that order, and the ada filter left exactly the row whose name has it. The sort raised the column and the direction before the count, so a header that listens to those two can draw its arrow before the rows move. The negative total sorts first ascending, and the decimal comparison is the reason 10.00 sits below 340.50.
Exercises
- Add a selected row count and a Sum of the visible totals, and print them after each filter.
- Change the filter to a case-sensitive one and add a step to the run that shows the difference on ada.
- Make SortBy stable for equal totals and explain which LINQ call gives that.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does the view model keep two collections?
Answer
One is every row, the other is the filtered and sorted view the grid binds to
A filter rebuilds the visible list without losing the file order.
-
Why does the filter setter return early for the same text?
Answer
A keystroke that did not change the filter is not a new filter
The text box raises an event per keystroke.
-
Which column type does the grid need for its own sorting?
Answer
A data source that implements sorting; BindingList does not
The form sorts through the view model instead.
-
What does SortBy do when the same column is named twice?
Answer
It reverses the direction
The run shows the same column ascending and then descending.
-
What did the ada filter leave visible?
Answer
A-1 Ada Lovelace
Only the name contains ada.
-
Which property change comes before Count in a filter?
Answer
Filter
The setter raises the filter first, then rebuilds.
-
How many errors did the view model count?
Answer
1
The negative total is the one invalid row.
-
Which call tells the grid that the whole visible list changed?
Answer
ResetBindings
A filter is a whole-list change.
-
Why is the total compared with CompareTo and not as a string?
Answer
A string comparison would put 10.00 before 2.00
The sort is numeric.
-
Which rows does the view model skip when it loads?
Answer
A row with the wrong column count or an unparseable total
The validator reports them, and the grid shows the rest.
Every listing on this page is plain .NET code with no window in it: it was built and run with the .NET SDK 10.0.303 on Alpine Linux 3.24.3 (x86_64) in a Docker container, and the output printed below the program is that run. The WinForms pages of this course are built for net10.0-windows against Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed and never run on Linux: WinForms needs Windows.
Article author: Arthur Isaev