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:
pri
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);
}
private void setRowNumber(DataGridView dgv)
{
foreach (DataGridViewRow row in dgv.Rows)
{
row.HeaderCell.Value = (row.Index + 1).ToString();
}
}
This worked for me.
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();
}
}
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
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();
}