【问题标题】:Can't Identify Values of DataGridViewCheckBoxCell无法识别 DataGridViewCheckBoxCell 的值
【发布时间】:2014-05-08 04:39:47
【问题描述】:

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

【问题讨论】:

    标签: c# datagridview datagridviewcheckboxcell


    【解决方案1】:

    也许不是这个问题的正确解决方案,但对我来说是有用的以获得单元格检查值:

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

    使用此代码:

    DataGridViewCheckBoxCell currentCell = (DataGridViewCheckBoxCell)dataGridView.CurrentCell;
    if ((bool)currentCell.EditedFormattedValue)
         //do sth
    else
         //do sth
    

    【讨论】:

      【解决方案2】:
      DataGridView.Rows[0].Cells[0].Value = true; 
      or 
      DataGridView.Rows[0].Cells[0].Value = false; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-08
        • 2021-12-12
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多