How to verify if a DataGridViewCheckBoxCell is Checked

前端 未结 7 1589
小鲜肉
小鲜肉 2021-01-11 10:45

I have bound a data table to a DataGridView, this data table has a column called \"Status\" which is of type Boolean. I can set the value to

相关标签:
7条回答
  • 2021-01-11 11:22
    bool checked = cell.Value as bool? ??  false;
    
    0 讨论(0)
  • 2021-01-11 11:25

    Another issue that may be encountered is this:

    When the user clicks the cell to check or uncheck the box, the underlying value will not be changed until the cell loses focus.

    This will not be an issue if the code in question is in a button, since the cell will lose focus when you click the button. But if your code is fired from a timer, you may still be checking the 'old' value.

    See my other answer here: https://stackoverflow.com/a/22080846/1015072

    0 讨论(0)
  • 2021-01-11 11:28

    I have no prior experience in this, but I guess you should check the value of the column or property.

    Try to have a look to this example:

    http://programmingwithstyle.blogspot.com/2007/06/how-to-get-from-datagridviewcheckboxcel.html

    0 讨论(0)
  • 2021-01-11 11:32

    CbxCell.Value must be equal to DBNull.Value (your column can contain null values right?)

    I would check for DBNull before casting:

    if (!DBNull.Value.Equals(CbxCell.Value) && (bool)CbxCell.Value == true)
    {
        //Do stuff
    }
    else
    {
        //Do Stuff
    }
    
    0 讨论(0)
  • 2021-01-11 11:36
     if (Convert.ToBoolean(dgvScan.Rows[rowIndex].Cells["Status"].Value))
    {
    //Do Something
    }
    else {
    // Do Something
    }
    
    0 讨论(0)
  • 2021-01-11 11:38

    Thank you all. Had the same problem but i find out that writing senderGrid.EndEdit(), before checking the value, resolves it.

    private void dgvRiscos_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;
            senderGrid.EndEdit();
    
            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn &&
                e.RowIndex >= 0)
            {
    
                var cbxCell = (DataGridViewCheckBoxCell)senderGrid.Rows[e.RowIndex].Cells["associado"];
                if ((bool)cbxCell.Value)
                {
                       // Criar registo na base de dados
                }
                else
                {
                       // Remover registo da base de dados
                }
            }
        }
    

    Keep up the good work

    0 讨论(0)
提交回复
热议问题