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

Csharp相关问答推荐

更改对象的旋转方向

使用yaml将Azure函数代码部署到FunctionApp插槽时出现问题(zip未找到)

程序集.加载从exe的异常

一种安全的方式来存储SSH凭证(MAUI/C#应用程序)

System.Text.Json数据化的C#类映射

Azure Function应用(. NET 8)不将信息记录到应用洞察

Blazor服务器端的身份验证角色

无法通过绑定禁用条目

使用HttpResponseMessage中的嵌套列表初始化JSON

.NET并发词典交换值

Swagger没有显示int?可以为空

Regex字母数字校验

HelperText属性不支持复杂内容(混合C#和标记)

当try 测试具有协变返回类型的抽象属性时,类似功能引发System.ArgumentException

如何在.NET MAUI中最大化GraphicsView的大小?

如何强制新设置在Unity中工作?

Linq SELECT的多条指令

DropDownListFor未显示选定值

如何处理ASP.NET Core中包含两个构造函数的控制器?

如何获取我在SQL中输入的值