无法在UI上以编程方式检查或取消选中DataGridViewCheckBoxColumn单元格

时间:2014-10-13 09:22:15

标签: c# checkbox datagridview

我已经在DataGridView上添加了DataGridViewCheckBoxColumn。 我还添加了两个按钮,一个用于选择所有复选框,一个用于取消选择所有复选框。

单击单击并选择/取消选择所有按钮单独工作,但是,如果我选择一个单击鼠标的单元格(在UI上选中复选框),然后按下取消选择 - 全部,则不起作用按钮复选框的值已更改,但UI上的复选框仍保持选中状态。

这是我的代码 单击

 private void dictionaryDataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if ((e.ColumnIndex == dictionaryDataGrid.Columns["ColSel"].Index) && (e.RowIndex >= 0))
             dictionaryDataGrid.Rows[e.RowIndex].Cells["ColSel"].Value = !(bool)(dictionaryDataGrid.Rows[e.RowIndex].Cells["ColSel"].Value == null ? false : dictionaryDataGrid.Rows[e.RowIndex].Cells["ColSel"].Value);

    }

按钮全选:

 private void btn_selAll_Click(object sender, EventArgs e)
        {
            for (int i = 1; i <= dictionaryDataGrid.Rows.Count; i++)
            {
                dictionaryDataGrid.Rows[i - 1].Cells["ColSel"].Value = true;
            }
        }

按钮取消全选:

private void btn_unselAll_Click(object sender, EventArgs e)
{
    for (int i = 1; i <= dictionaryDataGrid.Rows.Count; i++)
    {
        dictionaryDataGrid.Rows[i - 1].Cells["ColSel"].Value = false;
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

    private void btn_unselAll_Click(object sender, EventArgs e)
        {
            dictionaryDataGrid.ClearSelection();

            foreach (DataGridViewRow row in dictionaryDataGrid.Rows)
            {
                ((DataGridViewCheckBoxCell)row.Cells["ColSel"]).Value = false;
            }
    }