DataGridView行变色

效果直接在DataGridView的属性中可以设置,选中记录时的模式是选择整行即可。

 

 

要求是选中的行变色,代码如下

事件是RowPrePaint。

这个思路是先得到当前的行。RowPrePaint事件应该是每Paint一行之前的事件,所以对行进行检查,如果满足要求就设置成想要的样式即可。因为要把非当前行还原样式,所以记录了之前的颜色,估计直接记录Style也是一种好方法。

  1.         void DataGridView1RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
  2.         {
  3.             if (e.RowIndex >= dataGridView1.Rows.Count - 1)
  4.                 return;
  5.             var row = (sender as DataGridView).Rows[e.RowIndex];
  6.             try
  7.             {
  8.                 Color oldForeColor = new Color();
  9.                 Color oldBackColor = new Color();
  10.                 if (row == (sender as DataGridView).CurrentRow) {
  11.                     if(row.DefaultCellStyle.ForeColor != Color.White)
  12.                     {
  13.                         oldForeColor = row.DefaultCellStyle.ForeColor;
  14.                         row.DefaultCellStyle.ForeColor = Color.White;
  15.                     }
  16.                     if(row.DefaultCellStyle.BackColor != Color.Blue)
  17.                     {
  18.                         oldBackColor = row.DefaultCellStyle.BackColor;
  19.                         row.DefaultCellStyle.BackColor = Color.Blue;
  20.                     }
  21.                 }
  22.                 else
  23.                 {
  24.                     row.DefaultCellStyle.ForeColor = oldForeColor;
  25.                     row.DefaultCellStyle.BackColor = oldBackColor;
  26.                 }
  27.             }
  28.             catch (Exception)
  29.             {
  30.             }
  31.         }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值