2012-11-29 83 views
4

我正在致力於DataGridView,名爲ListingGrid,嘗試激活/停用已在DataGridViewCheckBoxColumn內的任何DataGridViewCheckBoxCell上「檢查過」的用戶。從DataGridViewCheckBoxCell獲取價值

這是即時通訊的方式試圖做的是:

foreach (DataGridViewRow roow in ListingGrid.Rows) 
{ 
    if ((bool)roow.Cells[0].Value == true) 
    { 
     if (ListingGrid[3, roow.Index].Value.ToString() == "True") 
     { 
      aStudent = new Student(); 
      aStudent.UserName = ListingGrid.Rows[roow.Index].Cells[2].Value.ToString(); 
      aStudent.State = true; 
      studentList.Add(aStudent); 

     } 
    } 
} 

據我得到的,當你檢查DataGridViewCheckBoxCell,該單元格的值是true吧?但它不允許我將該值轉換爲布爾值,然後進行比較,並向我拋出一個無效的轉換異常。

+0

HTTP的可能重複: //stackoverflow.com/questions/1563190/how-to-verify-if-a-datagridviewcheckboxcell-is-checked –

+0

也許並不完全與此問題有關,但這可能有所幫助:https://stackoverflow.com/a/48465766/5750078 – Loaderon

回答

13

嘗試:

DataGridViewCheckBoxCell chkchecking = roow.Cells[0] as DataGridViewCheckBoxCell; 

    if (Convert.ToBoolean(chkchecking.Value) == true) 
{ 
} 

DataGridViewCheckBoxCell chkchecking = roow.Cells[0] as DataGridViewCheckBoxCell; 

     if ((bool)chkchecking.Value == true) 
    { 
    } 
+0

「as DataGridViewCheckBoxCell;」工作很棒,謝謝! –

+1

即使它有效,也不需要投射到DataGridViewCheckBoxCell。你可以簡單地做「Convert.ToBoolean(roow.Cells [0] .Value);」 – Anonymous

+1

第一個解決方案適用於我,第二個解決方案沒有。可能是什麼問題呢?只是好奇。 –

-1

我覺得== true是沒有用的,你必須檢查你的電池是不是DBNull

if (chkchecking.Value != DBNull.Value)