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

时间:2014-11-04 12:29:10

标签: 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;
        }
    }
}

请帮忙。

谢谢,

1 个答案:

答案 0 :(得分:19)

您可以使用行的IsNewRow属性:

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