0

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

2 回答 2

2

特别是对于这个问题可能不是正确的解决方案,但对我来说很有用以获得单元格检查值:

使用事件 CellContentClick 而不是 CellClick。第一个仅在正确单击检查时触发,第二个在单元格的任何部分单击时触发,这是一个问题。此外,由于任何原因 DataGridViewCheckBoxCell.EditedFormattedValue 使用 CellClick 错误地返回其值,我们将使用 EditedFormattedValue。

使用此代码:

DataGridViewCheckBoxCell currentCell = (DataGridViewCheckBoxCell)dataGridView.CurrentCell;
if ((bool)currentCell.EditedFormattedValue)
     //do sth
else
     //do sth
于 2018-01-26T16:44:21.097 回答
0
DataGridView.Rows[0].Cells[0].Value = true; 
or 
DataGridView.Rows[0].Cells[0].Value = false; 
于 2014-05-08T08:49:10.747 回答