实现方式如下:
private void dgvRelation_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
try
{
SolidBrush b = new SolidBrush(this.dgvRelation.RowHeadersDefaultCellStyle.ForeColor);
e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture),
this.dgvRelation.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
}
catch { return; }
}
效果如下:

注意:使用该方式处理编号列的显示,需要处理cell_click事件,如: if (e.RowIndex == -1||e.ColumnIndex==-1) return;
升个级
/// <summary>
/// 重绘DataGridView
/// </summary>
/// <param name="dgv"></param>
/// <param name="e"></param>
public void PaintDgv(DataGridView dgv, DataGridViewRowPostPaintEventArgs e)
{
try
{
SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor);
e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture),
dgv.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 5, e.RowBounds.Location.Y + 4);
// 改变第一列列头内容
dgv.TopLeftHeaderCell.Value = dgv.RowCount.ToString();
dgv.TopLeftHeaderCell.ToolTipText = "查询数据总量为:" + dgv.RowCount.ToString() + "(条)";
}
catch { return; }
}


方式二:通过处理RowStateChanged事件实现
public void SetDgvNumCloByRowStateChanged(DataGridView dgv, DataGridViewRowStateChangedEventArgs e)
{
int rowCounts = dgv.Rows.Count;
if (rowCounts > 0)
{
for (int i = 0; i < rowCounts; i++)
{
dgv.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
// 改变第一列列头内容
dgv.TopLeftHeaderCell.Value = dgv.RowCount.ToString();
dgv.TopLeftHeaderCell.ToolTipText = "查询数据总量为:" + dgv.RowCount.ToString() + "(条)";
}
}
设置首列列头字体颜色
/// <summary>
/// 重绘DataGridView
/// </summary>
/// <param name="dgv"></param>
/// <param name="e"></param>
public void PaintDgv(DataGridView dgv, DataGridViewRowPostPaintEventArgs e)
{
try
{
SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor);
e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture),
dgv.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 5, e.RowBounds.Location.Y + 4);
// 改变第一列列头内容
dgv.EnableHeadersVisualStyles = false;//允许更改行、列头的字体颜色
dgv.TopLeftHeaderCell.Value = dgv.RowCount.ToString();
dgv.TopLeftHeaderCell.Style.ForeColor = Color.Salmon;
dgv.TopLeftHeaderCell.Style.Font = new Font("微软雅黑", 10, FontStyle.Bold);
dgv.TopLeftHeaderCell.ToolTipText = "查询数据总量为:" + dgv.RowCount.ToString() + "(条)";
}
catch { return; }
}
博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!

浙公网安备 33010602011771号