c# - 如何更改Datagridview行标题

标签 c# datagridview

datagridview 很好地显示了数据,但我想按顺序查看数字而不是行标题处的指针。

enter image description here

如图所示,标题单元格中有一个箭头。我不想这样,当我编写下面的代码时,只有当鼠标悬停在数字上时才会出现数字。

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString();
}

我想直接在行标题中看到它,如下图所示

enter image description here

最佳答案

您可以自己绘制行标题:

private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    // Draw only if the cell is the row header: e.ColumnIndex == -1
    // and the row is not the column header: e.RowIndex >= 0
    if (e.ColumnIndex == -1 && e.RowIndex >= 0) {
        bool isSelected = (e.State & DataGridViewElementStates.Selected) != 0;
        e.PaintBackground(e.ClipBounds, isSelected);
        var grid = (DataGridView)sender;
        if (e.RowIndex == grid.CurrentRow.Index) {
            e.PaintContent(e.ClipBounds); // Paints the selection arrow
        }

        var g = e.Graphics!;
        TextRenderer.DrawText(g, $"{e.RowIndex + 1}\u00a0", grid.Font, e.CellBounds,
            grid.ForeColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
        e.Handled = true;
    }
}

我使数字向右对齐并垂直居中。 “\u00a0” 是一个不间断空格,它使行号与行标题单元格右边缘的距离最小。

我尝试了g.DrawStringTextRenderer.DrawText。后一种使文本看起来与网格的其余部分更加一致,并绘制更清晰的文本。

enter image description here

关于c# - 如何更改Datagridview行标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77510409/

相关文章:

C#:填充 DataGridView 字段的宽度并在需要时添加滚动条

c# - 在 DataGridView 上托管自定义控件,这些控件从 DataTable 填充数据

c# - 如何手动触发 Datagridview.cellValidating?

c# - 当条件为真时,LINQ to 对象是否停止处理 Any()?

c# - ASP.NET MVC 4 连接两个表

c# - 如何将图像更新到不同的线程?

c# - new[] 和 new string[] 有什么区别?

c# - 数据 GridView Winforms : FullRowSelect current cell still visible

c# - 将 ComboBox 添加到特定行的 datagridview

c# - 从 C# 调用 C DLL 函数 - 将 char 参数转换为字符串