首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法识别DataGridViewCheckBoxCell的值

无法识别DataGridViewCheckBoxCell的值
EN

Stack Overflow用户
提问于 2014-05-08 12:39:47
回答 2查看 1.1K关注 0票数 0

所以我在这里看到了几个帖子,我尝试了所有的解决方案,但都没有效果。我已经在网上尝试了几个例子,但都没有成功。它在嘲笑我!下面的代码就是我现在运行的代码,我觉得它应该可以工作,但它不能工作。问题是,如果值不是true或false,那么它就会因为无效的强制转换而崩溃,因为值显示为{}。如果该值为true,则在cell.Value = cell.TrueValue的情况下,它永远不会被标识为true。我在datagridview设置中将TrueValue和FalseValue分别设置为true和false。我错过了什么?

代码语言:javascript
复制
       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仍未正常工作。

更新的代码

代码语言:javascript
复制
            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解决的

最终代码:

代码语言:javascript
复制
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 = "";
        }
EN

回答 2

Stack Overflow用户

发布于 2018-01-27 00:44:21

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

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

使用以下代码:

代码语言:javascript
复制
DataGridViewCheckBoxCell currentCell = (DataGridViewCheckBoxCell)dataGridView.CurrentCell;
if ((bool)currentCell.EditedFormattedValue)
     //do sth
else
     //do sth
票数 2
EN

Stack Overflow用户

发布于 2014-05-08 16:49:11

代码语言:javascript
复制
DataGridView.Rows[0].Cells[0].Value = true; 
or 
DataGridView.Rows[0].Cells[0].Value = false; 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23532860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档