2017-05-09 3 views
1

Ich möchte Zellen in DataGridView zusammenfassen und das Ergebnis in einer MessageBox anzeigen.C# datagridview Summe Zellen Wert

Ich habe zwei DataGridViews. Das erste DataGridView ruft Daten aus der Datenbank ab. Die zweite DataGridView ruft Werte ab, nachdem ich eine Zeile aus der ersten DataGridView ausgewählt habe.

Dies ist mein Code

private void actionStatistics_Click(object sender, EventArgs e) 
    { 
     int total = 0; 

     for (int i = 0; i < productsDataGridView.Rows.Count; i++) 
     { 
      total += int.Parse(productsDataGridView.Rows[i].Cells[6].Value.ToString()); 
     } 

     MessageBox.Show("Total quantity: " + total); 
    } 

ich Fehler in dieser Zeile erhalten:

 total += int.Parse(productsDataGridView.Rows[i].Cells[6].Value.ToString()); 

Fehler ist:

 An unhandled exception of type 'System.NullReferenceException' occurred in task3.exe. 
    Additional information: Object reference not set to an instance of an object. 

Kann mir jemand helfen, eine Lösung zu finden?

+1

Ich denke, das Problem ist, dass die Zelle [6] hat keinen Wert – jcvegan

Antwort

0

prüft für einen Nullwert vor der Zugabe:

total += int.Parse(productsDataGridView.Rows[i].Cells[6]?.Value?.ToString()); 

Oder die alte Art und Weise:

for (int i = 0; i < productsDataGridView.Rows.Count; i++) 
     { 
      if(productsDataGridView.Rows[i].Cells[6] !=null && productsDataGridView.Rows[i].Cells[6].Value != null) 
      { 
       total +=  int.Parse(productsDataGridView.Rows[i].Cells[6].Value.ToString()); 
      } 
     } 
0
  1. Die Zelle [i, 6] ist null, eine Bedingung, um zu überprüfen.
  2. Es ist eine bessere Praxis, auch zu überprüfen, ob der Wert eine Zahl ist, denn wenn es keine Zahl ist, erhalten Sie eine Ausnahme (bei Verwendung Parse() und nicht TryParse()). hier ist ein Beispiel, wie man es mit extension method macht.

    private void actionStatistics_Click(object sender, EventArgs e) 
        { 
         int total = 0; 
    
         for (int i = 0; i < productsDataGridView.Rows.Count; i++) 
         { 
          if (productsDataGridView.Rows[i].Cells[6] != null && (productsDataGridView.Rows[i].Cells[6].Value.ToString().IsNumeric())) 
          { 
           total += int.Parse(productsDataGridView.Rows[i].Cells[6].Value.ToString()); 
          } 
         } 
    
         MessageBox.Show("Total quantity: " + total); 
        } 
    
    } 
    public static class ExtensionMethods 
    { 
        public static bool IsNumeric(this string s) 
        { 
         float output; 
         return float.TryParse(s, out output); 
        } 
    } 
    
Verwandte Themen