https://learn.microsoft.com/zh-cn/dotnet/desktop/winforms/controls/implementing-virtual-mode-jit-data-loading-in-the-datagrid?view=netframeworkdesktop-4.8

主要参考上面链接的教程

主要步骤:

1 设置 DataGridView 的一些属性

this.dgv.ReadOnly                 = true;
this.dgv.AllowUserToAddRows       = false;
this.dgv.AllowUserToOrderColumns  = true;
this.dgv.AllowUserToResizeColumns = true;

this.dgv.ColumnHeadersHeightSizeMode =  DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dgv.RowHeadersWidthSizeMode     =  DataGridViewRowHeadersWidthSizeMode.DisableResizing;
this.dgv.AutoSizeColumnsMode         =  DataGridViewAutoSizeColumnsMode.DisplayedCells;
this.dgv.VirtualMode                 =  true;
dgv.SelectionMode                    =  DataGridViewSelectionMode.FullRowSelect;

2 加载数据,比如加载了一个DataTable

3 设置列和行数

foreach (DataColumn column in table.Columns) {
    dgv.Columns.Add(column.ColumnName, column.ColumnName);
}

this.dgv.RowCount = table.Rows.Count;
this.dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);

4 响应值设置事件

 private void DgvOnCellValueNeeded(object? sender, DataGridViewCellValueEventArgs e) {
        if (dataTableCurrent == null) {
            e.Value = null;
            return;
        }

        try {
            e.Value = dataTableCurrent.Rows[e.RowIndex][e.ColumnIndex];
        } catch (Exception exception) {
            Log.Error("DgvOnCellValueNeeded", exception);
        }
    }

标签: datagridview, 虚拟, 虚拟模式