创建虚拟模式以从 C# 中的字符串数组或 List 填充 DataGridView
本文关键字:List string DataGridView 填充 数组 字符串 模式 虚拟 创建 | 更新日期: 2023-09-27 18:30:28
当我用存储在string[] myData
中的行填充DataGridView
(在for
循环中)时,系统开始使用过多的RAM,GUI冻结,有时我会收到内存不足异常错误。
我已经读到虚拟模式按需填充数据网格视图并使用更少的 RAM。
但是,我找到的每个示例都使用数据库(或其他数据源)。我的值是从文件中读取并存储在数组变量中的字符串值:
string[] myData = obj.GetFileContent(file);
到目前为止我尝试过:
dataGridView1.VirtualMode = true;
创建了DataGridViewCellValueEventHandler
:
private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
//...
}
我的DataGridView
有 6 列,读取的文件大小约为 1GB。我试图跟随这个线程,但无法弄清楚如何使用我的string[] myData
来填充 DataGridView。
编辑:
文件行作为元素读取并存储在数组中。所以数组中的第一个元素是文件中的第一行,依此类推。稍后我将使用某种排序(正则表达式)将行的某些部分排序到列中。
数组元素放置在列中,如下所示:
for(int i = 0; i < myData.Count(); i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = (i + 1); //first column
dataGridView1.Rows[i].Cells[5].Value = myData[i]; //sixth column
}
我只想填充数据网格视图中可以显示的数据量。仅当用户向下滚动(和向上滚动)时,才应填充更多数据。
你没有得到VirtualMode
的概念:你不必填充DataGridView
的行和单元格。
在初始化DataGridView
时,只需设置行数:DataGridView.RowCount = myData.Length;
然后,实现 CellValueNeeded
事件处理程序或您的DataGridView
:
private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
if (e.ColumnIndex == 0)
e.Value = e.RowIndex + 1;
else if (e.ColumnIndex == 5)
e.Value = myData[e.RowIndex];
}