在使用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;
}