1

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 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?

1
  • Have you considered implementing a paging system? Commented Feb 28, 2011 at 17:08

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.