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
- DataGridViewTextBoxColumn: the default, for text and numbers. DefaultCellStyle.Format decides how the value is shown.
- DataGridViewCheckBoxColumn: a bool or a CheckState. ThreeState gives the indeterminate box.
- DataGridViewComboBoxColumn: a list per cell, with DataSource or Items. The value it stores is the selected item, which is why a combo column usually binds to objects.
- DataGridViewButtonColumn: a button per row, reported in CellContentClick rather than in the cell's value.
- DataGridViewImageColumn and DataGridViewLinkColumn: an image and a link. The link raises CellContentClick with the row it belongs to.
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
- Rows, Columns and the indexer _grid[row, column].Value: the cell. The value of an unbound cell is an object, so reading a number means a cast to decimal or an int.
- CurrentCell and CurrentRow: the cell with the focus, which is not the same as the selected cells. CellEnter and SelectionChanged report the difference.
- CellValueChanged: a value was committed, by an edit or by code. CellValidating is the veto, which is where a rule about a column goes.
- SelectedRows and SelectedCells: the selection, which with FullRowSelect is rows. MultiSelect allows more than one.
- AllowUserToAddRows and AllowUserToDeleteRows: the empty row at the bottom and the Delete key. Both default to true, which is wrong for a view over data the program owns.
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
- Add a fourth column with a different type and value, and run the program.
- Make the size column editable and print the editable count again.
- 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.
-
Which class is a grid column of text?
Answer
DataGridViewTextBoxColumn
The column types are TextBox, CheckBox, ComboBox, Button, Image and Link.
-
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.
-
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.
-
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.
-
Which is the cell with the focus?
Answer
CurrentCell
The current cell is not necessarily a selected one.
-
Which event can refuse an edit?
Answer
CellValidating, with e.Cancel
CellValueChanged reports a committed value and cannot take it back.
-
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.
-
What did the run print for the Size column?
Answer
1,200 with a thousand separator
The N0 format of the invariant culture.
-
Which column type raises CellContentClick for its button?
Answer
DataGridViewButtonColumn
A link column reports a click the same way.
-
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