2014-05-08 123 views
0

所以我在這裏看到了幾個帖子,我試過每個解決方案都無濟於事。我在網上嘗試了幾個例子,但都沒有成功。這是在嘲笑我!下面的代碼就是我現在運行的東西,我覺得應該可以工作,但事實並非如此。問題是,如果值不是真或假,那麼由於值顯示爲{},導致無效投射。如果該值爲true,那麼它在cell.Value = cell.TrueValue時從未被識別爲真。我將datagridview設置中的TrueValue和FalseValue分別設置爲true和false。我錯過了什麼?無法識別DataGridViewCheckBoxCell的值

 DataGridViewCheckBoxCell cell = 
      (DataGridViewCheckBoxCell) ((DataGridView) sender).Rows[e.RowIndex].Cells[e.ColumnIndex]; 

     if (cell.ValueType == typeof(bool)) 
     { 
      if (cell.Value != null && !(bool)cell.Value) 
       cell.Value = cell.TrueValue; 
      else 
       cell.Value = cell.FalseValue; 

     } 

我想我終於得到了它的一部分。 cell.Value == DBNull.Value爲新的處女複選框。 cell.Value == cell.FalseValue仍然不起作用。

更新的代碼

  if (cell.ValueType == typeof (bool)) 
      { 
       if (cell.Value == DBNull.Value || cell.Value == cell.FalseValue) 
       { 
        cell.Value = cell.TrueValue; 
       } 
       else if ((bool)cell.Value) 
       { 
        cell.Value = cell.FalseValue; 
       } 
      } 

我終於揭穿它。最後一個問題是使用Convert.ToBoolean(cell.Value)==假的,而cell.Value == cell.FalseValue克服

終極密碼:

DataGridViewCheckBoxCell cell = 
      (DataGridViewCheckBoxCell)((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex]; 

     if (cell.ValueType != typeof (bool)) return; 

     if (cell.Value == DBNull.Value || Convert.ToBoolean(cell.Value) == false) 
     { 
      cell.Value = cell.TrueValue; 
      ((DataGridView)sender).Rows[e.RowIndex].Cells["Comment"].Value = "Not in source."; 
     } 
     else 
     { 
      cell.Value = cell.FalseValue; 
      ((DataGridView)sender).Rows[e.RowIndex].Cells["Comment"].Value = ""; 
     } 

回答

0
DataGridView.Rows[0].Cells[0].Value = true; 
or 
DataGridView.Rows[0].Cells[0].Value = false; 
1

也許不是正確的解決方案這個問題特別有用,但爲了獲得單元格檢查值對我很有用:

使用事件CellContentClick而不是CellClick。第一個觸發只有當檢查被正確點擊時,第二個觸發點擊任何部分的單元格,這是一個問題。除了任何原因DataGridViewCheckBoxCell.EditedFormattedValue與CellClick錯誤地返回它的值,我們將使用EditedFormattedValue。

使用此代碼:

DataGridViewCheckBoxCell currentCell = (DataGridViewCheckBoxCell)dataGridView.CurrentCell; 
if ((bool)currentCell.EditedFormattedValue) 
    //do sth 
else 
    //do sth