2016-02-20 27 views
1

GridView中有複選框列,字符串值「P」正在檢查中。所以,我想計算具有相同「P」值的該列的所有行。我想下面的代碼:想要在GridView的列中獲得總共相同的字符串值

int sumP = 0; 
public void countpresent() //To count all Present Students in the gridview 
{ 
    for (int i = 0; i < (dgvAttendance.Rows.Count-1); i++) 
    { 
     if (dgvAttendance.Rows[i].Cells["Present"].Value.ToString() == "P") 
     { 
      sumP += 1; 
     } 
    } 
    lblPresent.Text = sumP.ToString(); 
} 

它正在爲所有的刺「P」,但是當它顯示null值,它拋出一個異常「notset一個對象的實例對象引用」。在異常詳細信息中顯示「NullReferenceException」。 請任何一個建議的東西,以幫助

回答

1

它拋出一個異常,因爲:

dgvAttendance.Rows[i].Cells["Present"].Value 

爲空,你不能做一個空值.ToString()

您可以檢查,這不是空第一:

if (dgvAttendance.Rows[i].Cells["Present"].Value != null && 
    dgvAttendance.Rows[i].Cells["Present"].Value.ToString() == "P") 

與C#6你可以在一行做到這一點:

if (dgvAttendance.Rows[i].Cells["Present"].Value?.ToString() == "P") 

?對於!= null &&

+0

感謝您的建議和充分的解釋。非常感謝您 –

3
手短

您可能想要在執行操作之前檢查dgv行是否爲空:

在C#6:

if (dgvAttendance.Rows[i].Cells["Present"].Value?.ToString() == "P") 
    { 
     sumP += 1; 
    } 

或者在舊的版本:

if (dgvAttendance.Rows[i].Cells["Present"].Value != null && dgvAttendance.Rows[i].Cells["Present"].Value?.ToString() == "P") 
    { 
     sumP += 1; 
    } 

或者實際上,在老版本的,你可以嘗試使用Convert.ToString,因爲它是設計用來處理空

if (Convert.ToString(dgvAttendance.Rows[i].Cells["Present"].Value) == "P") 
    { 
     sumP += 1; 
    } 
+0

我們爲什麼要使用價值?這裏。請解釋一下 –

+0

?檢查值是否爲空。如果是這樣,那麼以後將不執行ToString。但是,如果它不爲空,那麼ToString將被執行。它是C#6中的一種合成糖,恰好適用於您的情況。否則,我們應該像在「較舊版本」中顯示的那樣寫入,這是較長的。請記住,當您的值爲空時,您無法對其執行ToString,因爲您無法將ToString執行爲null。 – Ian

+0

非常感謝。這有助於我學習這一點。謝謝 –

相關問題