9

I am working on a DataGridView called ListingGrid trying to activate / deactivate users that have been "checked" on any DataGridViewCheckBoxCell that is inside the DataGridViewCheckBoxColumn.

This is the way im trying to do that :

foreach (DataGridViewRow roow in ListingGrid.Rows)
{
    if ((bool)roow.Cells[0].Value == true)
    {
        if (ListingGrid[3, roow.Index].Value.ToString() == "True")
        {
            aStudent = new Student();
            aStudent.UserName = ListingGrid.Rows[roow.Index].Cells[2].Value.ToString();
            aStudent.State = true;
            studentList.Add(aStudent);

        }
    }
}

As far as I get, when you check a DataGridViewCheckBoxCell, the value of the cell is true right? But it is not allowing me to convert the value to bool and then compare it, throwing me an invalid cast exception.

GSerg
  • 76,472
  • 17
  • 159
  • 346

4 Answers4

20

try:

DataGridViewCheckBoxCell chkchecking = roow.Cells[0] as DataGridViewCheckBoxCell;

    if (Convert.ToBoolean(chkchecking.Value) == true)
{
}

or

DataGridViewCheckBoxCell chkchecking = roow.Cells[0] as DataGridViewCheckBoxCell;

        if ((bool)chkchecking.Value == true)
    {
    }
Developer
  • 2,987
  • 10
  • 40
  • 51
  • the " as DataGridViewCheckBoxCell;" worked marvellous, thank you! – Bryan Arbelo - MaG3Stican Nov 29 '12 at 19:03
  • 1
    There is no need to cast to a DataGridViewCheckBoxCell even though it works. You can simply do "Convert.ToBoolean(roow.Cells[0].Value);" – Anonymous Apr 09 '14 at 08:37
  • 2
    The first solution worked for me, the second one didn't. What could be the problem? Just curious. – susieloo_ Sep 15 '14 at 20:21
  • This only works for me if I add the lines`code` var senderGrid = (DataGridView)sender; `code` senderGrid.EndEdit(); before checking the value (see [link](https://stackoverflow.com/questions/1563190/how-to-verify-if-a-datagridviewcheckboxcell-is-checked)) – chrmue Feb 05 '21 at 11:30
1

Tried different options, same code sometimes worked and some other times it did not. Upon extensive debugging, it turned out that the root cause is not with the checkbox fetching code but the datagridvew mechanism itself.

The value of checkbox in the active/selected row was never received properly. If the datagridview has only one row, this issue can not be detected.

myDataGridViewName.EndEdit();

This has to be called before reading the cell values. After that the simple statements in the approved answer were enough.

Convert.ToBoolean(chkchecking.Value)

or

(bool)chkchecking.Value

both worked fine as expected. The credit for this tip goes to another answer to a similar question.

BiLaL
  • 708
  • 11
  • 18
0

I think == true is not useful and you have to check if your cell is not DBNull :

if (chkchecking.Value != DBNull.Value)
Jesse Johnson
  • 1,638
  • 15
  • 25
Pruno
  • 11
0

I do it usually like this bool value = (short)chkchecking.Value == 1

Nabil
  • 1