[英]C# DataGridView cell update not updating last row
我有一個按鈕,該按鈕使用組合框中選擇的內容更新第3列(C)(標題除外)中的所有值。
private void updateExcel_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
if (!RowIsEmpty(i))
{
dataGridView1[2, i].Value = Combo.Text;
}
}
}
除了不更新最后一行外,這還行得通。
RowIsEmpty:
private bool RowIsEmpty(int rowIndex)
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (dataGridView1.Rows[rowIndex].Cells[i].Value != null &&
dataGridView1.Rows[rowIndex].Cells[i].Value.ToString() != "")
{
return false;
}
}
return true;
}
我認為您的問題出在updateExcel_Click
。
我認為問題在於:
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
因為您要在此處跳過行,所以假設dataGridView1.RowCount
的值為3,並且使dataGridView1.RowCount - 1
dataGridView1.RowCount = 2
。
這樣,您的for將會運行0、1和2。在我看來,目標是您想要他運行0、1、2和3。
您在問題上說的問題是:不更新最后一行,因為for正在跳過最后一行。
解:
private void updateExcel_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
if (!RowIsEmpty(i))
{
dataGridView1[2, i].Value = Combo.Text;
}
}
}
或者,如果您想保留自己的邏輯,則需要添加<
,如下所示:
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.