c# - 如何跳过循环中自动添加到DataGridView的空行?

标签 c# datagridview

我有一个简单的 C# 应用程序,您必须在其中的 DataGridView 中输入数据。我已经为列实现了一些验证器,例如空值或非数字输入。我在 foreach (DataGridViewRow row in dataGridView1.Rows) {...}

按下按钮后进行检查

我面临的问题是它还尝试验证 DataGridView 的最后一行,尽管这一行是自动添加的并且是空的。所以我在这里陷入了一个循环......

private void button1_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        string inputItemNr;
        string inputMHD;
        string inputCharge;
        string inputSupplNr;
        string inputPrnCnt;
        UInt32 itemnr;
        DateTime mhd;
        string mhdFormat = "yyMMdd";
        string batch;
        byte prncnt;

        if (row.Cells[0].Value == null)
        {
            MessageBox.Show("Enter item number");
            return;
        }
        else
        {
            inputItemNr = row.Cells[0].Value.ToString();
        }

        if (!UInt32.TryParse(inputItemNr, out itemnr))
        {
            MessageBox.Show("Incorrect item number: " + inputItemNr);
            return;
        }

        if (row.Cells[1].Value == null)
        {
            MessageBox.Show("Enter MHD");
            return;
        }
        else
        {
            inputMHD = row.Cells[1].Value.ToString();
        }

        if (!DateTime.TryParseExact(inputMHD, mhdFormat, CultureInfo.InvariantCulture,
            DateTimeStyles.None, out mhd))
        {
            MessageBox.Show("Incorrect MHD: " + inputMHD);
            return;
        }

        if (row.Cells[2].Value == null)
        {
            inputCharge = DateTime.Now.ToString("yyMMdd");
        }
        else
        {
            inputCharge = row.Cells[2].Value.ToString();
        }

        if (row.Cells[3].Value == null)
        {
            batch = inputCharge;
        }
        else
        {
            inputSupplNr = row.Cells[3].Value.ToString();
            batch = inputCharge + " " + inputSupplNr;
        }

        if (row.Cells[4].Value == null)
        {
            inputPrnCnt = "1";
        }
        else
        {
            inputPrnCnt = row.Cells[4].Value.ToString();
        }

        if (!byte.TryParse(inputPrnCnt, out prncnt))
        {
            MessageBox.Show("Incorrect print count: " + inputPrnCnt);
            return;
        }
    }
}

请帮忙。

谢谢,

最佳答案

您可以使用 IsNewRow行的属性:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.IsNewRow) continue;
    // rest of your loop body ...
}

关于c# - 如何跳过循环中自动添加到DataGridView的空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26735188/

相关文章:

c# - 如何获取datagridview组合框的选定项的值

c# - datagridview cellclick 事件的工作原理类似于 cellcontentclick

vb.net - 如何使 DataGridViewComboBoxColumn 的 ComboBox 接受用户新项目?

c# - 有没有办法在 C# 中使用 OpenXml 库来固定列的宽度?

c# - 如何匹配从给定索引开始的正则表达式?

C# Expression.Lambda 无法在运行时编译

c# - 查找具有特定类型的属性并将其返回

C# 捕获异常

c# - 实用程序类与子类化 .net 控件

c# - DataGridView - 如何连接到与单元格更改关联的事件?