Hwj's blog - 虚拟
type: channel
link: https://blog.hwj.im/index.php/tag/%E8%99%9A%E6%8B%9F/
items: 设置DataGridView的虚拟模式

设置DataGridView的虚拟模式
type: item
date: 2024-03-05T22:21:02+08:00
description: 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 加载数据,比如加载了一个DataTable3 设置列和行数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); } }