使用Nullable类型:布尔值

时间:2012-09-19 18:04:27

标签: c#

我在DataGridView的列中有一个复选框。现在我得到了一个例外,因为没有选中复选框。我不知道如何处理它?<​​/ p>

 private void uncheckGrid(ref DataGridView dgv, int index)
    {
        try
        {
            foreach (DataGridViewRow row in dgv.Rows)
            {
                DataGridViewCheckBoxCell check = row.Cells[1] as DataGridViewCheckBoxCell;
                if (check.Value != null) // throw an exception here.
                {
                    if ((bool)check.Value)
                    {
                        Int32 intVal = Convert.ToInt32(row.Cells[0].Value);
                        if (intVal == index)
                        {
                            check.Value = false;
                        }
                    }
                }
            }

感谢。

1 个答案:

答案 0 :(得分:3)

DataGridViewCheckBoxCell check = row.Cells[1] as DataGridViewCheckBoxCell;是隐式演员。它可能返回null,因为行单元格不是真正的DataGridViewCheckBoxCell

在强制转换后的if语句中添加一个附加条件:

if (check != null && check.Value != null)
{ /* Do stuff here */ }
相关问题