vendredi 7 août 2015

InvalidCastException when casting a CheckBox cell in DataGridView

After sorting a DataGridView (dgv), I would like to make rows that have the CheckBox cell named "Deleted" invisible. This sometimes gives the InvalidCastException when casting that CheckBox cell's value to bool.

    private void dgv_Sorted(object sender, EventArgs e)
    {
        //hide rows that are marked 'Deleted' when user clicks header to 
        if (dgv.DataSource != null && dgv.RowCount > 1)
        {
            foreach (DataGridViewRow row in dgv.Rows)
            {
                //An unhandled exception of type 'System.InvalidCastException' occurred. Additional information: Specified cast is not valid.
                if (row.Cells["Deleted"].Value == null ? false : (bool)row.Cells["Deleted"].Value)
                {
                    dgv.CurrentCell = null;
                    row.Visible = false;
                }
            }
        }
    }

When I hover over row.Cells["Deleted"].Value, it's value is {}. I thought the only states a checkbox cell could be in are null, unchecked and checked. What does {} mean here? Any suggestion on how to fix this would be appreciated.




Aucun commentaire:

Enregistrer un commentaire