DataGridView单元格重绘后不能选中

在使用DataGridView时候,单元格重绘是在所难免的,但是有时候重绘后会出现很多奇怪的问题。

其中一个就是单元格好像不能被选中,其实是可以被选中的,只是背景色没有变而已。

根本原因在与我们可能忘了处理单元格选中状态时需要绘制不同的背景颜色。

注意:重绘一定要把e.Handled设为true, 要不然重绘没有任何效果(被系统重绘覆盖)

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
       DataGridView dgv = (DataGridView)sender;
       //绘制背景色:如果选中那就用选中的蓝色背景色,否则用默认白色背景色
       if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected)
                   e.Graphics.FillRectangle(new SolidBrush(dgv.DefaultCellStyle.SelectionBackColor), e.CellBounds.X - 1, e.CellBounds.Y - 1, e.CellBounds.Width, e.CellBounds.Height);
       else
                   e.Graphics.FillRectangle(new SolidBrush(dgv.DefaultCellStyle.BackColor), e.CellBounds.X - 1, e.CellBounds.Y - 1, e.CellBounds.Width, e.CellBounds.Height);
       //绘制边框
       e.Graphics.DrawRectangle(new Pen(dgv.GridColor, 1), e.CellBounds.X-1, e.CellBounds.Y-1, e.CellBounds.Width, e.CellBounds.Height);
       StringFormat sf = new StringFormat();
       sf.Alignment = StringAlignment.Center;
       sf.LineAlignment = StringAlignment.Center;
       e.Graphics.DrawString("●", new Font("Arial", 12, FontStyle.Regular), Brushes.Gray, e.CellBounds, sf);
       //告知系统此单元格已经重绘,系统不需要再次重绘
       e.Handled = true;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值