DataGridView显示行号,设置行和列的颜色
程序员文章站
2024-01-04 08:20:28
...
首先设置dataGridView的RowPostPaint事件,然后添加如下代码:
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
// 在DataGridView中显示行号
using (SolidBrush b = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
{
e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentUICulture), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
}
DataGridViewRow dgr = dataGridView1.Rows[e.RowIndex];
if (dgr.Cells["x1"].Value?.ToString() == "")
{
dgr.DefaultCellStyle.BackColor = Color.Pink;//设置行颜色
}
if (dgr.Cells["x2"].Value.ToString() == "")
{
dgr.Cells["x2"].Style.BackColor = Color.Yellow;//设置列颜色
}
}
推荐阅读