开发者

Adding a lot of rows in DataGridView causes System.OutOfMemoryException

开发者 https://www.devze.com 2023-02-13 18:21 出处:网络
I am using this code to add rows to my DataGridView from a comma separated formatted string. public void addRows(ArrayList keywords)

I am using this code to add rows to my DataGridView from a comma separated formatted string.

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;
    }
}

I get the error:

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

Additional information: Out of memory.

When the开发者_JAVA技巧 rows count is >4000.

I commented each part of the code and found that when I comment this part:

    /*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();*/

The error doesn't occur.

Why is this error happening and how could I avoid it?


Don't add the rows manually to the DGV, use either data binding or virtual mode. With either approach, only visible rows will be created, which avoids creating thousands of UI objects


Usually big grid has to be treated by using virtuial data mode.

0

精彩评论

暂无评论...
验证码 换一张
取 消