两种方法,代码如下:
void initDataGridView()
{
Stopwatch sw = new Stopwatch();//Stopwatch提供一组方法和属性,可用于准确地测量运行时间
sw.Start();
//方法一:一行一行增加到datagridview中
for (int i = 0; i < 10000; i++)
{
int RowIndex = dataGridView1.Rows.Add();
dataGridView1.Rows[RowIndex].Cells[ColumnIndex.Name].Value = (i + 1).ToString();
dataGridView1.Rows[RowIndex].Cells[ColumnName.Name].Value = "Name" + (i + 1).ToString();
dataGridView1.Rows[RowIndex].Cells[ColumnJobNumber.Name].Value = "JobNumber" + (i + 1).ToString();
dataGridView1.Rows[RowIndex].Cells[ColumnSex.Name].Value = "Man";
dataGridView1.Rows[RowIndex].Cells[ColumnRemark.Name].Value = "Remark" + (i + 1).ToString();
}
sw.Stop();
TimeSpan dts = sw.Elapsed;//获取当前实例测量得出的总运行时间
Console.WriteLine("function1 use time:{0}", dts);
sw.Restart();
//方法二:先定义一个DataGridViewRow队列,然后赋值,然后一次性添加所有行到datagridview中
DataGridViewRow[] dtRows = new DataGridViewRow[10000];
for (int i = 0; i < 10000; i++)
{
dtRows[i] = new DataGridViewRow();
dtRows[i].CreateCells(dataGridView2);
dtRows[i].Cells[0].Value = (i + 1).ToString();
dtRows[i].Cells[1].Value = "Name" + (i + 1).ToString();
dtRows[i].Cells[2].Value = "JobNumber" + (i + 1).ToString();
dtRows[i].Cells[3].Value = "Man";
dtRows[i].Cells[4].Value = "Remark" + (i + 1).ToString();
}
dataGridView2.Rows.AddRange(dtRows);
sw.Stop();
dts = sw.Elapsed;//获取当前实例测量得出的总运行时间
Console.WriteLine("function2 use time:{0}", dts);
}
执行之后的耗时对比结果如下:
function1 use time:00:00:06.8457473
function2 use time:00:00:00.7253520