因此,我在这里看到了几篇帖子,并且尝试了所有解决方案均无济于事。我在网上尝试了几个例子,但没有任何效果。这是在嘲讽我!下面的代码是我现在正在运行的代码,我认为它应该可以工作,但事实并非如此。问题是如果该值不是真或假,那么它会因无效转换而爆炸,因为该值显示为 {}。如果该值为真,那么它永远不会被识别为真,其中 cell.Value = cell.TrueValue。我在 datagridview 设置中将 TrueValue 和 FalseValue 分别设置为 true 和 false。我错过了什么?
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) == false 而不是 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 = "";
}