大家一致在讨论如何做一个DataGridView控件汇总的行在最末,有的自己加上一行,把最后一行覆盖掉,有的在控件外部空间加上汇总的信息,都不是最佳的解决方案。
找到了一个老外的网址,才发现和人家比,我们还是有差距的。http://www.dotnetmonster.com/Uwe/Forum.aspx/winform-data-binding/1245/DataGridView-Summary-Row
用这个思路来解决DataGridView汇总行的问题,非常不错,排序等操作也不会影响最后一行,我梢后会扩展到以前发布的控件DataGridViewEx内http://download.csdn.net/detail/ireenter/3407133 ,到时分享给大家。
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{///原文没有,但必需增加上。
this.dataGridView1.AllowUserToAddRows = true;
int sum = 0;
// only draw the cells of the extra row by ourselves, leaving the rest cells to the systemif (e.RowIndex == this.dataGridView1.NewRowIndex && e.ColumnIndex > -1)
{
for (int i = 0; i < this.dataGridView1.NewRowIndex; i++)
{
if (this.dataGridView1.Rows[i].Cells[e.ColumnIndex].Value.ToString().Trim() != "")
{
sum += (int)this.dataGridView1.Rows[i].Cells[e.ColumnIndex].Value;
}
}
e.PaintBackground(e.CellBounds, false);
e.Graphics.DrawString(sum.ToString(), this.dataGridView1.Font, Brushes.Black, e.CellBounds.Left + 2,e.CellBounds.Top + 2);
e.Handled = true;
}
}