在DataGridView的行标题中显示行号

时间:2012-03-06 10:16:16

标签: c# .net winforms datagridview

是否可以在DataGridView的行标题中显示行号?

我正在尝试使用此代码,但它不起作用:

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

我是否必须设置一些DataGridView属性?

11 个答案:

答案 0 :(得分:51)

您还可以在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);
}

答案 1 :(得分:47)

似乎它没有把它变成一个字符串。 试试

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

答案 2 :(得分:9)

谢谢@Gabriel-Perez和@Groo,好主意!如果其他人想要它,这是在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

您还可以获取默认字体rowFont = grid.RowHeadersDefaultCellStyle.Font,但它可能看起来不太好。下面的截图使用的是Tahoma字体。

Example on windows 7

答案 3 :(得分:9)

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

这对我有用。

答案 4 :(得分:5)

只是增强上面的解决方案..所以标题自我调整宽度以适应像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);
}

答案 5 :(得分:4)

你可以这样做:

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

    dgv.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

}

答案 6 :(得分:1)

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

当应用于具有大量行的datagridview时会产生内存泄漏,最终会导致内存不足问题。任何想法如何回收记忆?

以下是应用于包含某些列的空网格的示例代码。它只是添加行和数字索引。重复按钮几次。

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();
    }
}

答案 7 :(得分:0)

这对我有用。

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

答案 8 :(得分:0)

这项工作,用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;
        }
    }

答案 9 :(得分:0)

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();
   }
}

答案 10 :(得分:0)

基于以下视频:VB.net-Auto generate row number to datagridview in windows application-winforms,您可以设置数据源,并且此代码放置行号,就像超级按钮一样。

private void DataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // Add row number
    (sender as DataGridView).Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex+1).ToString();
}