在DataGridView中添加大量行会导致System.OutOfMemoryException

时间:2011-02-28 16:56:28

标签: c# .net visual-studio-2010 memory out-of-memory

我正在使用此代码从逗号分隔的格式化字符串向我的DataGridView添加行。

public void addRows(ArrayList keywords)
{
    try
    {
        foreach (string keyword in keywords)
        {
            bool already_exists = false;

            string[] row = keyword.Split(',');

            foreach (DataGridViewRow row2 in keywords_grid.Rows)
            {
                string keyword2 = keywords_grid.Rows[row2.Index].Cells[0].Value.ToString().Trim();

                if (row[0] == keyword2)
                {
                    already_exists = true;
                    continue;
                }
            }

            if (already_exists) continue;

            int n = keywords_grid.Rows.Add();

            keywords_grid.Rows[n].Cells[0].Value = row[0];
            keywords_grid.Rows[n].Cells[1].Value = row[1];
            keywords_grid.Rows[n].Cells[2].Value = getSourceIcon(row[2]);
            keywords_grid.Rows[n].Cells[2].ToolTipText = row[2].Trim().ToUpper();

            gridChanged = true;
        }
    }
    catch (Exception ex){}
}

private Icon getSourceIcon(string _color)
{
    string color = _color.ToLower();

    switch (color)
    {
        case "red":
            return Properties.Resources.red_icon;
        case "yellow":
            return Properties.Resources.yellow_icon;
        case "green":
            return Properties.Resources.green_icon;
        case "user input":
            return Properties.Resources.user_input_icon;
        default:
            return Properties.Resources.user_input_icon;
    }
}

我收到错误:

An unhandled exception of type 'System.OutOfMemoryException' occurred in System.Windows.Forms.dll

Additional information: Out of memory.

当行数为> 4000时。

我评论了代码的每一部分,发现当我评论这部分时:

    /*int n = keywords_grid.Rows.Add();

    keywords_grid.Rows[n].Cells[0].Value = row[0];
    keywords_grid.Rows[n].Cells[1].Value = row[1];
    keywords_grid.Rows[n].Cells[2].Value = getSourceIcon(row[2]);
    keywords_grid.Rows[n].Cells[2].ToolTipText = row[2].Trim().ToUpper();*/

不会发生错误。

为什么会发生这种错误,我该如何避免呢?

2 个答案:

答案 0 :(得分:1)

通常必须使用虚拟数据模式处理大网格。

答案 1 :(得分:1)

请勿手动将行添加到DGV,使用data bindingvirtual mode。无论使用哪种方法,都只会创建可见行,这样可以避免创建数千个UI对象

相关问题