'Why does a DataGridView crash

If I run this code first...

        private void offToolStripMenuItem_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow dgvOff in dgv_Off.Rows)
        {
            dgvOff.Cells[0].Value = 0;
        }
        foreach (DataGridViewRow dgvOn in dgv_On.Rows)
        {
            dgvOn.Cells[0].Value = 0;
        }
    }

Then I run this code my app crashes.

        private void dgv_Off_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0)
        {
            foreach (DataGridViewRow row in dgv_Off.SelectedRows)
            {
                if (row.Cells[0].Value != null)
                {
                    row.Cells[0].Value = !(bool)row.Cells[0].Value;
                }
                else
                {
                    row.Cells[0].Value = true;
                }
            }
        }
    }

It's crashing at this line.

row.Cells[0].Value = !(bool)row.Cells[0].Value;

Any help would be appreciated. Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source