简体   繁体   English

在 DataGridView 的行标题中显示行号

[英]Show row number in row header of a DataGridView

Is it possible to show row number in the row header of a DataGridView ?是否可以在DataGridView的行标题中显示行号?

I'm trying with this code, but it doesn't work:我正在尝试使用此代码,但它不起作用:

    private void setRowNumber(DataGridView dgv)
    {
        foreach (DataGridViewRow row in dgv.Rows)
        {
            row.HeaderCell.Value = row.Index + 1;
        }
    }

Do I have to set some DataGridView property?我是否必须设置一些DataGridView属性?

You can also draw the string dynamically inside the RowPostPaint event:您还可以在RowPostPaint事件中动态绘制字符串:

private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat() 
    { 
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center, 
        LineAlignment = StringAlignment.Center
    };

    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

It seems that it doesn't turn it into a string.似乎它没有把它变成一个字符串。 Try尝试

row.HeaderCell.Value = String.Format("{0}", row.Index + 1);

Thanks @Gabriel-Perez and @Groo, great idea!谢谢@Gabriel-Perez 和@Groo,好主意! In case others want it, here's a version in VB tested in Visual Studio 2012. In my case I wanted the numbers to appear top right aligned in the Row Header.如果其他人需要它,这里有一个在 Visual Studio 2012 中测试过的 VB 版本。在我的情况下,我希望数字在行标题中显示为右上角对齐。

Private Sub MyDGV_RowPostPaint(sender As Object, _
    e As DataGridViewRowPostPaintEventArgs) Handles MyDataGridView.RowPostPaint

    ' Automatically maintains a Row Header Index Number 
    '   like the Excel row number, independent of sort order

    Dim grid As DataGridView = CType(sender, DataGridView)
    Dim rowIdx As String = (e.RowIndex + 1).ToString()
    Dim rowFont As New System.Drawing.Font("Tahoma", 8.0!, _
        System.Drawing.FontStyle.Bold, _
        System.Drawing.GraphicsUnit.Point, CType(0, Byte))

    Dim centerFormat = New StringFormat()
    centerFormat.Alignment = StringAlignment.Far
    centerFormat.LineAlignment = StringAlignment.Near

    Dim headerBounds As Rectangle = New Rectangle(_
        e.RowBounds.Left, e.RowBounds.Top, _
        grid.RowHeadersWidth, e.RowBounds.Height)
    e.Graphics.DrawString(rowIdx, rowFont, SystemBrushes.ControlText, _
        headerBounds, centerFormat)
End Sub

You can also get the default font, rowFont = grid.RowHeadersDefaultCellStyle.Font , but it might not look as good.您还可以获得默认字体rowFont = grid.RowHeadersDefaultCellStyle.Font ,但它可能看起来不那么好。 The screenshot below is using the Tahoma font.下面的屏幕截图使用的是 Tahoma 字体。

Windows 7 上的示例

private void setRowNumber(DataGridView dgv)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        row.HeaderCell.Value = (row.Index + 1).ToString();
    }
}

This worked for me.这对我有用。

just enhancing above solution.. so header it self resize its width in order to accommodate lengthy string like 12345只是增强上述解决方案.. 所以标题它会自动调整其宽度以适应像 12345 这样的长字符串

private void advancedDataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat()
    {
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center,

        LineAlignment = StringAlignment.Center
    };
    //get the size of the string
    Size textSize = TextRenderer.MeasureText(rowIdx, this.Font);
    //if header width lower then string width then resize
    if (grid.RowHeadersWidth < textSize.Width + 40)
    {
        grid.RowHeadersWidth = textSize.Width + 40;
    }
    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

you can do this :你可以这样做 :

private void setRowNumber(DataGridView dgv)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        row.HeaderCell.Value = row.Index + 1;
    }

    dgv.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

}

row.HeaderCell.Value = row.Index + 1; row.HeaderCell.Value = row.Index + 1;

when applied on datagridview with a very large number of rows creates a memory leak and eventually will result in an out of memory issue.当应用于具有大量行的 datagridview 时,会导致内存泄漏并最终导致内存不足问题。 Any ideas how to reclaim the memory?任何想法如何回收内存?

Here is sample code to apply to an empty grid with some columns.这是应用于具有某些列的空网格的示例代码。 it simply adds rows and numbers the index.它只是添加行并为索引编号。 Repeat button click a few times.重复按钮点击几次。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        dataGridView1.SuspendLayout();
        for (int i = 1; i < 10000; i++)
        {
            dataGridView1.Rows.Add(i);                
        }
        dataGridView1.ResumeLayout();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
            row.HeaderCell.Value = (row.Index + 1).ToString();
    }
}

This worked for me.这对我有用。

Private Sub GridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles GridView1.CellFormatting
    Dim idx As Integer = e.RowIndex
    Dim row As DataGridViewRow = VDataGridView1.Rows(idx)
    Dim newNo As Long = idx
    If Not _RowNumberStartFromZero Then
        newNo += 1
    End If

    Dim oldNo As Long = -1
    If row.HeaderCell.Value IsNot Nothing Then
        If IsNumeric(row.HeaderCell.Value) Then
            oldNo = CLng(row.HeaderCell.Value)
        End If
    End If

    If newNo <> oldNo Then 'only change if it's wrong or not set
        row.HeaderCell.Value = newNo.ToString()
        row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
    End If
End Sub

This work in C# :这项工作在C# 中

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    int idx = e.RowIndex;
    DataGridViewRow row = dataGridView1.Rows[idx];
    long newNo = idx;
    if (!_RowNumberStartFromZero)
        newNo += 1;

    long oldNo = -1;
    if (row.HeaderCell.Value != null)
    {
        if (IsNumeric(row.HeaderCell.Value))
        {
            oldNo = System.Convert.ToInt64(row.HeaderCell.Value);
        }
    }

    if (newNo != oldNo)
    {
        row.HeaderCell.Value = newNo.ToString();
        row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
    }
}
private void ShowRowNumber(DataGridView dataGridView)
{
   dataGridView.RowHeadersWidth = 50;
   for (int i = 0; i < dataGridView.Rows.Count; i++)
   {
        dataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
   }
}

Based on this viedo: VB.net-Auto generate row number to datagridview in windows application-winforms , you can set the DataSource and this code puts the rows numbers, works like a charm.基于此视频: VB.net-Auto 在 windows application-winforms 中为 datagridview 生成行号,您可以设置 DataSource 并且此代码放置行号,就像一个魅力。

private void DataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // Add row number
    (sender as DataGridView).Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex+1).ToString();
}
Private Sub DataGridView1_RowPostPaint(sender As Object, e As DataGridViewRowPostPaintEventArgs) Handles DataGridView1.RowPostPaint
        Dim rowIdx = (e.RowIndex + 1).ToString()
        Dim centerFormat = New StringFormat With {.Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center}
        Dim textSize As Size = TextRenderer.MeasureText(rowIdx, sender.Font)
        If (sender.RowHeadersWidth < textSize.Width + 35) Then
            sender.RowHeadersWidth = textSize.Width + 35
        End If
        Dim headerBounds = New Rectangle(e.RowBounds.Left, e.RowBounds.Top, sender.RowHeadersWidth, e.RowBounds.Height)
        e.Graphics.DrawString(rowIdx, sender.Font, SystemBrushes.ControlText, headerBounds, centerFormat)
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM