zoukankan      html  css  js  c++  java
  • DataGridView 斑马线样式

    前言

    在数据展示控件中为了使数据显示更加醒目,一般都会为数据显示控件增加样式。本文主要介绍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下测试。

  • 相关阅读:
    糗事百科图片爬取
    Linux文件和目录常用命令
    复习
    Win7的快捷键
    开始运行中的快捷键
    TextBox客户端JS赋值 后台获取(转载)
    window.returnValue的用法
    input的readonly属性与TextBox的ReadOnly和Enabled属性区别
    剖析 ADO.NET 批处理更新
    关于C#多线程的WaitHandle
  • 原文地址:https://www.cnblogs.com/Johnny_Z/p/2096880.html
Copyright © 2011-2022 走看看