C#.NET foreach skips first row of DataGridView when changing Row HeaderCell value

321 Views Asked by At

I'm trying to show the row number on DataGridView RowHeader, but when I do the following block of code it doesn't change the first row row.HeaderCell.Value, but it will change all the next. When I watch the row variable and the gridView.Rows[0], the gridView.Rows[0] doesn't change at all and the row gets clear like it's a new row.

foreach (DataGridViewRow row in gridView.Rows)
{
    row.HeaderCell.Value = (row.Index + 1).ToString();
}

Weirdly, if I change the gridView.Rows[0].HeaderCell.Value before entering the loop, this line will be "ignored", but the loop will work just fine and change the HeaderCells of all rows.

gridView.Rows[0].HeaderCell.Value = "";
foreach (DataGridViewRow row in gridView.Rows)
{
    row.HeaderCell.Value = (row.Index + 1).ToString();
}

It looks like you need to change the first row once to "unlock" the subsequent changes.

What could be going on to this issue?

Thank you all

EDIT:

This is a Windows Application on .NET Framework 4.8 And I forgot to show the steps before the problem.

bs = new BindingSource();
bs.DataSource = table;
IBindingListView bindingList = bs;
gridView.DataSource = bindingList;
gridView.Visible = true;

foreach (DataGridViewRow row in gridView.Rows)
{
    row.HeaderCell.Value = (row.Index + 1).ToString();
}
1

There are 1 best solutions below

0
Karen Payne On

If you don't have a lot of records try the following. I'd call this clunky but it may suit you?

In form shown or load event

dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader;
dataGridView1.CellFormatting += DataGridView1OnCellFormatting;

Then add this code to the form

private void DataGridView1OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    var grid = sender as DataGridView;
    if (!(grid.Rows[e.RowIndex].IsNewRow))
    {
        grid.Rows[e.RowIndex].HeaderCell.Value = Convert.ToString(e.RowIndex + 1);
    }
}

enter image description here