[英]C#.NET foreach skips first row of DataGridView when changing Row HeaderCell value
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.我试图在 DataGridView RowHeader 上显示行号,但是当我执行以下代码块时,它不会更改第一行 row.HeaderCell.Value,但会更改所有下一行。 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.当我观察
row
变量和gridView.Rows[0]
时, gridView.Rows[0]
根本没有改变,并且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
,此行将被“忽略”,但循环将正常工作并更改所有行的 HeaderCells。
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.这是 .NET Framework 4.8 上的 Windows 应用程序,我忘了显示问题之前的步骤。
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();
}
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.