2011-02-28 70 views
1

我正在使用此代码将行从逗号分隔的格式化字符串添加到我的DataGridView。在DataGridView中添加大量行会导致System.OutOfMemoryException

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

不会发生错误。

为什么这个错误发生,我怎么能避免它?

+0

您是否考虑实施分页系统? – 2011-02-28 17:08:24

回答

1

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

1

通常情况下,大网格必须使用虚拟数据模式进行处理。

相关问题