我正在使用此代碼將行從逗號分隔的格式化字符串添加到我的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();*/
不會發生錯誤。
爲什麼這個錯誤發生,我怎麼能避免它?
您是否考慮實施分頁系統? – 2011-02-28 17:08:24