davioooh
davioooh

Reputation: 24676

Show row number in row header of a DataGridView

Is it possible to show row number in the row header of a 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?

Upvotes: 63

Views: 166868

Answers (13)

Zeeshan Ali
Zeeshan Ali

Reputation: 1

Simple way to count grid value just copy and paste your grid last

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

Upvotes: -1

user17661239
user17661239

Reputation: 1

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

Upvotes: 0

FcoJavier99
FcoJavier99

Reputation: 327

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.

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

Upvotes: 4

suriyadi
suriyadi

Reputation: 1

This work in 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;
    }
}

Upvotes: -1

Alireza815
Alireza815

Reputation: 359

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

}

Upvotes: 3

sm.abdullah
sm.abdullah

Reputation: 1802

just enhancing above solution.. so header it self resize its width in order to accommodate lengthy string like 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);
}

Upvotes: 13

M. Fawad Surosh
M. Fawad Surosh

Reputation: 480

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

Upvotes: -1

suriyadi
suriyadi

Reputation: 1

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

Upvotes: -1

mihZR
mihZR

Reputation: 826

It seems that it doesn't turn it into a string. Try

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

Upvotes: 65

Samir Emdanat
Samir Emdanat

Reputation: 9

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

Upvotes: 0

timthez
timthez

Reputation: 174

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

This worked for me.

Upvotes: 9

Rob Sherratt
Rob Sherratt

Reputation: 131

Thanks @Gabriel-Perez and @Groo, great idea! 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.

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. The screenshot below is using the Tahoma font.

Example on windows 7

Upvotes: 13

Gabriel Perez
Gabriel Perez

Reputation: 801

You can also draw the string dynamically inside the RowPostPaint event:

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

Upvotes: 80

Related Questions