2014-11-04 13 views
6

我有一個簡單的C#應用​​程序,您必須在其中輸入數據在DataGridView。我已經爲列實現了一些驗證器,如空值或非數字輸入。我按了一個按鈕後進行檢查foreach (DataGridViewRow row in dataGridView1.Rows) {...}如何跳過自動添加到循環中的DataGridView的空行?

我面臨的問題是它也試圖驗證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; 
     } 
    } 
} 

請幫助。

感謝,

回答

14

您可以使用該行的IsNewRow屬性:

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

作品,謝謝! – Geo 2014-11-04 12:42:41

+0

除非措辭恰到好處,否則通過谷歌很難找到這些信息;直到你的回答引起我的注意,我才知道這個屬性存在。非常感謝分享這個非顯而易見的,但令人驚訝的簡單提示。 – 2017-04-18 19:59:31