0

I'm having a problem with my .net application where I'm trying to take a value from a DataTable cell and cast it to a bool.
The DataTable is bound to a DataGridView and the cell is a CheckBox.
When I check if that cell is null, it returns as not null. However when I try to get the value, it returns nothing and will not cast it to a bool.

Any help appreciated.

        private void dgvItems_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2 || e.ColumnIndex == 3)
            {
                var test = dtItems.Rows[e.RowIndex][e.ColumnIndex];               

                if (test != null)
                {
                    if ((bool)test)
                    {
                        MessageBox.Show("true");
                    }
                    else
                    {
                        MessageBox.Show("false");
                    }
                }
                else
                {
                    MessageBox.Show("null");
                }
            }
        }

Exception thrown at (bool)test:
System.InvalidCastException: 'Specified cast is not valid.'

enter image description here

9
  • 1
    Could the value actually be DBNull rather than Null? Commented Sep 6, 2018 at 8:49
  • Potentially. Let me check. Commented Sep 6, 2018 at 8:53
  • What exactly is DBNull? Commented Sep 6, 2018 at 8:54
  • 1
    If Dt is a DataTable being mapped, and in your database value is null and a not a Boolean, then it will show as DbNull Commented Sep 6, 2018 at 8:57
  • 1
    @PaulAlexander DBNull is a non existent value from a database learn.microsoft.com/en-us/dotnet/api/… Commented Sep 6, 2018 at 8:57

1 Answer 1

1

DataGrid Cells are ThreeWay Checkbox. They cannot be casted to bool.

Try bool? instead

  bool? testValue=(bool?) dtItems.Rows[e.RowIndex][e.ColumnIndex];    
  if (testValue!=null&&testValue)
  {
     MessageBox.Show("true");
  }
  else
  {
      MessageBox.Show("false");
  }
Sign up to request clarification or add additional context in comments.

3 Comments

throws an error: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
One question, As I rememebr, you need to dtItems.Rows[e.RowIndex][e.ColumnIndex].Value
I was missing the explicit cast operator (bool?).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.