DataGridView

A DataGridView is the control a business application is built around: a table of rows and columns that the user reads, sorts, edits and selects. It is the largest control in WinForms and this lesson takes the unbound part: the columns the program defines and the rows it adds. Binding it to a list is the subject of the two lessons after this one.

A grid filled by hand

using System; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly DataGridView _grid = new() { Dock = DockStyle.Fill, AllowUserToAddRows = false, AllowUserToDeleteRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, SelectionMode = DataGridViewSelectionMode.FullRowSelect, MultiSelect = false, }; public Form1() { Text = "Orders"; ClientSize = new Size(560, 300); _grid.Columns.Add(new DataGridViewTextBoxColumn { Name = "customer", HeaderText = "Customer", FillWeight = 50, }); _grid.Columns.Add(new DataGridViewTextBoxColumn { Name = "total", HeaderText = "Total", FillWeight = 20, DefaultCellStyle = new DataGridViewCellStyle { Format = "N2", Alignment = DataGridViewContentAlignment.MiddleRight }, }); _grid.Columns.Add(new DataGridViewCheckBoxColumn { Name = "paid", HeaderText = "Paid", FillWeight = 15, }); _grid.Rows.Add("Ada Lovelace", 1250.00m, true); _grid.Rows.Add("Grace Hopper", 340.50m, false); _grid.ReadOnly = true; Controls.Add(_grid); } }

dotnet build app.csproj

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

The listing is built and not run. A row added with Rows.Add fills the columns in order, so the order of the Columns.Add calls is the order of the arguments: a checkbox column that comes third means the third argument is a bool. Format = "N2" on the cell style is what makes 1250 a price with a thousand separator and two decimals; ReadOnly = true on the grid is the read-only view, and setting it per column or per cell is how a grid with one editable column is made.

The column types

A column has Name and HeaderText, and they are different: the name is the key the code and the data binding use, the header is what the user reads. AutoSizeColumnsMode.Fill makes the columns share the width, and FillWeight decides the share.

Rows, cells and the selection

The grid is a control with a lot of behaviour and a lot of events, and the two rules that keep it manageable are: values belong to a model, not to the cells, and a rule belongs to CellValidating rather than to a check after the user is done.

A typed table that runs

A grid is a list of typed columns over rows of values, and what it shows is a format of each value. This program prints one row through three column definitions, and it runs here:

using System; using System.Collections.Generic; using System.Globalization; using System.Linq; var columns = new List<Column> { new("Name", Editable: true, Width: 160), new("Size", Editable: false, Width: 80), new("Modified", Editable: false, Width: 120), }; var row = new Dictionary<string, object> { ["Name"] = "notes.txt", ["Size"] = 1200, ["Modified"] = new DateTime(2026, 11, 20), }; foreach (var column in columns) { Console.WriteLine($"{column.Name,-9} {Display(row[column.Name], column),-12} editable={column.Editable} width={column.Width}"); } Console.WriteLine($"total width: {columns.Sum(column => column.Width)}"); Console.WriteLine($"editable columns: {columns.Count(column => column.Editable)}"); static string Display(object value, Column column) => value switch { int number => number.ToString("N0", CultureInfo.InvariantCulture), DateTime date => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), _ => value.ToString() ?? string.Empty, }; internal sealed record Column(string Name, bool Editable, int Width);

dotnet run

Name      notes.txt    editable=True width=160
Size      1,200        editable=False width=80
Modified  2026-11-20   editable=False width=120
total width: 360
editable columns: 1

The output is the real run. The number is formatted with a thousand separator and the date with a fixed pattern, which is what a cell style does in the grid; the editable flag is the per-column ReadOnly, and the widths add up to the width the grid would give to AutoSizeColumnsMode.None. The Display function is the same switch a CellFormatting handler makes, without the event: one function that knows how a value of each type is read.

Exercises

  1. Add a fourth column with a different type and value, and run the program.
  2. Make the size column editable and print the editable count again.
  3. Explain from the documentation what CellValidating can do that CellValueChanged cannot.

Questions

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

  1. Which class is a grid column of text?

    Answer

    DataGridViewTextBoxColumn

    The column types are TextBox, CheckBox, ComboBox, Button, Image and Link.

  2. What defines the order of the arguments of Rows.Add?

    Answer

    The order of the Columns.Add calls

    Rows.Add fills the columns in the order they were added.

  3. Which property shows a number as a price?

    Answer

    DefaultCellStyle.Format = "N2"

    The cell style's format string is applied to every cell of the column.

  4. How is one column editable in an otherwise read-only grid?

    Answer

    ReadOnly = false on that column and true on the grid or the others

    ReadOnly exists on the grid, the column, the row and the cell.

  5. Which is the cell with the focus?

    Answer

    CurrentCell

    The current cell is not necessarily a selected one.

  6. Which event can refuse an edit?

    Answer

    CellValidating, with e.Cancel

    CellValueChanged reports a committed value and cannot take it back.

  7. What does AllowUserToAddRows = true add?

    Answer

    An empty row at the bottom for a new record

    It and AllowUserToDeleteRows default to true, which is wrong for a read-only view.

  8. What did the run print for the Size column?

    Answer

    1,200 with a thousand separator

    The N0 format of the invariant culture.

  9. Which column type raises CellContentClick for its button?

    Answer

    DataGridViewButtonColumn

    A link column reports a click the same way.

  10. What does FillWeight do with AutoSizeColumnsMode.Fill?

    Answer

    Decides the share of the width each column gets

    The weights are relative, not pixels.

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 logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev