DataGridView绑定CellPainting事件后行选中功能失效求助
DataGridView自定义CellPainting后单元格选中状态不显示的解决方法
问题出在你用的MSDN示例代码里,它直接固定使用e.CellStyle.BackColor填充单元格背景,完全没考虑单元格的选中状态。当行被选中时,自定义绘制的单元格不会自动切换到选中样式,导致视觉上没反应。
你需要修改代码,在绘制背景前先判断单元格是否处于选中状态,动态选择对应的背景色和文本颜色。下面是修复后的完整代码:
private void dataGridView1_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e) { if (this.dataGridView1.Columns["ContactName"].Index == e.ColumnIndex && e.RowIndex >= 0) { Rectangle newRect = new Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 1, e.CellBounds.Width - 4, e.CellBounds.Height - 4); // 根据选中状态获取正确的背景色和文本颜色 Brush backColorBrush; Brush textBrush; if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { backColorBrush = new SolidBrush(e.CellStyle.SelectionBackColor); textBrush = new SolidBrush(e.CellStyle.SelectionForeColor); } else { backColorBrush = new SolidBrush(e.CellStyle.BackColor); textBrush = new SolidBrush(e.CellStyle.ForeColor); } using (Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor), bgBrush = backColorBrush) { using (Pen gridLinePen = new Pen(gridBrush)) { // 绘制单元格背景(根据选中状态切换) e.Graphics.FillRectangle(bgBrush, e.CellBounds); // 绘制网格线(保留原逻辑) e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom); // 绘制内嵌高亮框(保留原逻辑) e.Graphics.DrawRectangle(Pens.Blue, newRect); // 绘制文本(根据选中状态切换颜色) if (e.Value != null) { e.Graphics.DrawString((string)e.Value, e.CellStyle.Font, textBrush, e.CellBounds.X + 2, e.CellBounds.Y + 2, StringFormat.GenericDefault); } e.Handled = true; } } } }
关键修改说明:
- 新增了选中状态判断:通过
e.State & DataGridViewElementStates.Selected检查单元格是否被选中 - 动态切换背景色:选中时使用
SelectionBackColor,未选中时用常规BackColor - 同步切换文本颜色:选中时用
SelectionForeColor,保证文本在选中背景下的可读性 - 保留了你原本需要的自定义绘制效果(蓝色高亮框、网格线)
这样修改后,自定义绘制的单元格就能正常显示选中状态了,和其他默认单元格的选中视觉效果保持一致。
内容的提问来源于stack exchange,提问作者21021
相关产品推荐
相关产品推荐

