Johnny_Z

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

前言

在数据展示控件中为了使数据显示更加醒目,一般都会为数据显示控件增加样式。本文主要介绍DataGridView数据控件显示斑马线样式思路。

内容

方法一:

自己编程实现。

在数据控件绑定完数据后,这里使用了DataGridView的RowPrePaint事件。该事件在发生任何单元格绘制之前,执行行绘制时引发的事件。

private void DataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if (sender is DataGridView)
{
DataGridView dgv
= (DataGridView)sender;
if((e.RowIndex+1)%2==0)//如果该行为2的倍数 则上色
{
dgv.Rows[e.RowIndex].DefaultCellStyle.BackColor
= Color.LightBlue;
}

}
}

使用上述代码后,可以看到DataGridView的样式已经为斑马线了。 但是,我们还要注意一个细节。当我们点击表头行时,往往会按照当前点击的列排序,这就打乱了我们已经画好的斑马线,所以我们应该在点击表头行时做点什么!

点击表头单元格时有两个事件共我们使用。一个是CellClick,另一个是CellMouseClick。简单说一下这两个的区别。

这里引用一段话:

“The CellClick event does not receive information about the mouse position. If the event handler needs information about the mouse position, use the CellMouseClick event”.

这个是CellMouseClick的DataGridViewCellMouseEventArgs的内容

这个是CellClick的DataGridViewCellEventArgs的内容

CellMouseClick事件包含了鼠标位置的相关信息。

这里采用CellMouseClick事件,当然也完全可以使用CellClick事件。

private void DataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if(sender is DataGridView)
{
DataGridView dgv
= (DataGridView) sender;
if (e.RowIndex == -1)//如果该行为表头
{
foreach (DataGridViewRow row in dgv.Rows)/*把所有行背景色职位白色*/
{
row.DefaultCellStyle.BackColor
= Color.White;
}
}
}
}

好了,这回点击表头也可以了。

方法二:

一击必杀。

其实DataGridView控件中已经实现了斑马线效果,就是AlternatingRowDefaultCellStyle属性,只要修改其属性的BackColor即可实现该效果。

另:本程序在.NET Framework3.5下测试。

posted on 2011-07-03 19:20  Johnny_Z  阅读(2010)  评论(0编辑  收藏  举报