2014-11-04 7 views
6

Ho una semplice applicazione C# in cui devi inserire i dati in un DataGridView. Ho implementato alcuni validatori per le colonne, come valori nulli o input non numerici. Effettuo i controlli dopo che un pulsante è stato premuto da foreach (DataGridViewRow row in dataGridView1.Rows) {...}Come saltare la riga vuota aggiunta automaticamente a DataGridView in un ciclo?

sto affrontando il problema che tenta anche di convalidare l'ultima riga del DataGridView, anche se questo viene aggiunto automaticamente ed è vuoto. Quindi sono bloccato in un loop qui ...

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; 
     } 
    } 
} 

Please help.

Grazie,

risposta

14

Si potrebbe utilizzare la proprietà IsNewRow della riga:

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

opere, grazie! – Geo

+0

Questa informazione è stata sorprendentemente difficile da trovare tramite Google a meno che non sia stata formulata correttamente; Non avevo idea che questa proprietà esistesse fino a quando la tua risposta non l'ha portato alla mia attenzione. Mille grazie per aver condiviso questo suggerimento non ovvio, ma sorprendentemente semplice. –