c# - C# DataGridView 单元格更新不更新最后一行
问题描述
我有一个按钮,它使用组合框中选择的任何内容更新第 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
。
有了这个,你的意志会运行 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 中添加 this <
,如下所示:
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
推荐阅读
- anylogic - 如何在 Ubuntu 操作系统中使用 USB 加密狗激活 AnyLogic?
- c# - 如何对打印到物理打印机的功能进行单元测试?
- r - 通过给定分布更改分类变量中字段的分布
- arrays - vertx 决定 jsonobject vs jsonarray
- python-3.x - 使用 matplotlib(或 seaborn)绘制 d 轨道图
- git - 如何创建新分支并将来自另一个分支的差异合并到其中,但单个目录除外
- machine-learning - coremltools管道输入节点未连接到模型的其余部分
- r - 为什么我使用 which() 函数时会输出 integer(0)?
- visual-studio - Visual Studio 2017 版本 15.9.4 中的 C++ 优化器错误?
- c# - PrimaryThenSecondary LocationMode 是否检查主要的 RA-GRS 是否存在?