所以我在這裏看到了幾個帖子,我試過每個解決方案都無濟於事。我在網上嘗試了幾個例子,但都沒有成功。這是在嘲笑我!下面的代碼就是我現在運行的東西,我覺得應該可以工作,但事實並非如此。問題是,如果值不是真或假,那麼由於值顯示爲{},導致無效投射。如果該值爲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 = "";
}