大家在使用DataGridView的时候,可能都想在最下面显示一行汇总行,在该行汇总行,可以对需要汇总的列进行汇总显示。
但是在网上查起来,实现方法都有各种各样的问题,没有办法,自己动手,丰衣足食。
废话不多说,直接上效果
且在汇总行始终处于最底下的行中,即使增加行或者点击了任意一个列头进行了排序,也需要保证在最底下。且在左右滚动的时候,要保证按照
原本的列对应关系显示。
实现方法:
对这个DataGridView进行重载。在新增加行的响应处理函数中,增加的行在汇总行的上面插入一行。
在列表头的排序处理中,始终将该汇总行放在最下面。
相关代码如下:
这个是在绘制"汇总行"时候的代码。这个可以保证显示的这个汇总行和其他行的颜色不一样。
void CMyDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{ //汇总行的TAG值标识为SUMMARYROW
if (this.Rows[e.RowIndex].Tag != null && this.Rows[e.RowIndex].Tag.ToString() == "SUMMARYROW")
{
this.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.DarkGray;
this.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
//自己输出字符串
float X, Y;
SizeF ssize = e.Graphics.MeasureString("汇总", this.DefaultCellStyle.Font);
X = e.RowBounds.X + (this.RowHeadersWidth - ssize.Width) / 2;
Y = e.RowBounds.Y + (this.Rows[e.RowIndex].Height - ssize.Height) / 2;
//这里在行表头前面显示红色的“汇总”两个字
e.Graphics.DrawString("汇总", this.DefaultCellStyle.Font, new SolidBrush(Color.Red), X, Y);
}
else
{
SolidBrush b = new SolidBrush(this.RowHeadersDefaultCellStyle.ForeColor);
e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), this.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
}
}
而对于排序则实现如下,这样就可以保证在用户点击列表头的时候不会将汇总行也作为数据行进行排序了,从而保证汇总行始终都是在最底下的一行:
public void CMyDataGridView_SortCompare(Object sender, DataGridViewSortCompareEventArgs e)
{
if (this.Rows[e.RowIndex1].Tag != null && this.Rows[e.RowIndex1].Tag.ToString() == "SUMMARYROW")
{
//ROW1>ROW2
e.SortResult = 1;
if (this.SortOrder == SortOrder.Descending)
e.SortResult = -1;
e.Handled = true;
return;
}
if (this.Rows[e.RowIndex2].Tag != null && this.Rows[e.RowIndex2].Tag.ToString() == "SUMMARYROW")
{
//ROW1<ROW2
e.SortResult = -1;
if (this.SortOrder == SortOrder.Descending)
e.SortResult = 1;
e.Handled = true;
return;
}
//其他的正常排序比较操作
....
}
而在新增行的时候,需要将新增的行放在汇总行前面。
同样也是为了保证该汇总行始终在最后一行显示。这个是因为设置了不允许用户手工增加新行。因为如果允许用户手工增加新行的话。在最后的行始终会是新增行。
因此,如果要实现允许用户新增行,则需要响应用户的键盘事件。处理用户的下箭头事件,以及回车事件。在事件处理中进行新增行的处理。
处理代码为在汇总行的前面插入一行。相关代码如下:
//因为是通过数据绑定方式来做的,添加数据的格式需要和数据库一致。否则会报错
//这里不考虑是否重复内容,由服务器将最后一条数据提交覆盖之前的。抑或报告错误?
//这些信息不会保存,也就是说一旦刷新或者关闭就没有了。呵呵。
dv.Rows.Insert(dv.Rows.Count-1, 1);