创建虚拟模式以从字符串数组填充DataGridView或在C#中填充List <string>

时间:2016-01-15 11:06:44

标签: c# memory datagridview

当我使用存储在DataGridView中的行填充for(在string[] myData循环中)时,系统开始使用太多RAM,GUI冻结,有时我得到 OutOfMemoryException 错误。

我已经读过虚拟模式按需填充DataGridView并使用更少的RAM。

但是,我发现的每个示例都使用数据库(或其他一些数据源)。我的值是字符串值,从文件中读取并存储在数组变量中:

string[] myData = obj.GetFileContent(file);

到目前为止我尝试过:

dataGridView1.VirtualMode = true;

创建了DataGridViewCellValueEventHandler

private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
          //...
}

我的DataGridView有6列,读取的文件大小约为1GB。我试过跟随 this thread,但无法弄清楚如何使用我的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
}

我想只填充可以在DataGridView中显示的数据。只有当用户向下(向上)滚动时,才会填充更多数据。

1 个答案:

答案 0 :(得分:0)

你没有得到VirtualMode的概念:你不必填写行和&amp; 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];
}