So I have seen several posts here and I have tried every solution to no avail. I have tried several examples all over the web and nothing has worked. It's taunting me! The below code is what I'm running now which I feel should work but it doesn't. The problem is if the value is not true or false then it blows up with invalid cast because the value is displayed as {}. If the value is true then it's never identified as true where cell.Value = cell.TrueValue. I set TrueValue and FalseValue in the datagridview setup as true and false respectively. What have I missed?
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;
}
I think I finally got part of it. cell.Value == DBNull.Value for a new virgin checkbox. cell.Value == cell.FalseValue is still not working.
Updated Code
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;
}
}
I finally nailed it. The last problem was overcome by using Convert.ToBoolean(cell.Value) == false rather cell.Value == cell.FalseValue
Final Code:
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 = "";
}
Maybe not the right solution for this problem in particular, but was useful for me in order to get the cell check value:
Use the event CellContentClick instead of CellClick. The first one triggers only when the check is correctly clicked, the second one triggers with a click in any part of the cell, which is a problem. Besides for any reason DataGridViewCheckBoxCell.EditedFormattedValue returns its value wrongly with CellClick, and we are going to use EditedFormattedValue.
Use this code:
DataGridViewCheckBoxCell currentCell = (DataGridViewCheckBoxCell)dataGridView.CurrentCell;
if ((bool)currentCell.EditedFormattedValue)
//do sth
else
//do sth
DataGridView.Rows[0].Cells[0].Value = true;
or
DataGridView.Rows[0].Cells[0].Value = false;
来源:https://stackoverflow.com/questions/23532860/cant-identify-values-of-datagridviewcheckboxcell