What is the VirtualMode in .NET WinForms DataGridView control?
Posted: (EET/GMT+2)
The built-in DataGridView control in WinForms can display large amounts of tabular data. If you work with large datasets, the VirtualMode option can help improve performance.
By default, DataGridView stores cell values internally or binds them to a data source such as a DataTable. This works well for normal use, but loading large tables can consume a lot of memory.
When VirtualMode is enabled, the grid does not store the data itself. Instead, it asks your code for the values when they are needed.
Enabling virtual mode requires setting the corresponding property to True:
dataGridView1.VirtualMode = true;
When this mode is enabled, the control raises events whenever it needs to read or write a cell value. The most commonly used one is the CellValueNeeded event. Here's an example:
dataGridView1.CellValueNeeded += DataGridView1_CellValueNeeded;
private void DataGridView1_CellValueNeeded(
object sender,
DataGridViewCellValueEventArgs e)
{
e.Value = myData[e.RowIndex][e.ColumnIndex];
}
In this example, the grid retrieves the value from an external data structure when a cell becomes visible.
This approach is useful when:
- The dataset is large (thousands of rows or more).
- You want to load rows on demand.
- The data comes from a comparatively slow source such as a database or a web/HTTP service.
Some things to keep in mind:
- You are responsible for managing the underlying data.
- Sorting and editing require additional event handling.
- The implementation is more complex than normal data binding.
For typical datasets, regular data binding is simpler. The VirtualMode option becomes useful
when performance or memory usage becomes a concern.