e.ColumnIndex == 3
只会在第三列触发的Paint事件中调用,也就是说,如果点击ColumnIndex =2的单元格触发Paint时,你的代码不起作用,会实用dataGridView2的默认样式绘制.
e.CellBounds,因为上面是第三列所以e.CellBounds始终是第三列的Bounds
--参考
if(e.ColumnIndex>=0&&e.ColumnIndex < 4 && e.RowIndex == 2)
{
Rectangle re =dataGridView1.GetCellDisplayRectangle(0,e.RowIndex,false);
re.Width = re.Width + dataGridView1.Columns[1].Width + dataGridView1.Columns[2].Width + dataGridView1.Columns[3].Width;
e.Graphics.FillRectangle(Brushes.Yellow,re);
Pen pen = new Pen(dataGridView1.BackgroundColor,1);
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
e.Graphics.DrawLine(pen,re.X,re.Y + re.Height - 1,re.X + re.Width,re.Y + re.Height - 1);
e.Graphics.DrawLine(pen,re.X + re.Width - 1,re.Y,re.X + re.Width - 1,re.Y + re.Height);
SizeF strSize = e.Graphics.MeasureString(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(),dataGridView1.Font);
e.Graphics.DrawString(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(),dataGridView1.Font,
Brushes.Black,re.X + (re.Width - strSize.Width) / 2,re.Y + (re.Height - strSize.Height) / 2); e.Handled = true;
}