如何在datagridview中处理组合框的事件?

时间:2016-10-02 15:27:32

标签: c# checkbox datagridcomboboxcolumn

我有一个复选框[All]和一个datagridview,如下所示:

enter image description here

我想:

  • 内部数据网格视图,如果选中所有复选框,则会选中复选框[All],否则如果未选中所有复选框,则取消选中复选框[All]
  • 内部数据网格视图,有一个未选中的复选框,未选中复选框[All]

我试了但是我无法做到:

private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    bool isAllCheck = false;

    if (e.ColumnIndex == 0)
    {
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            DataGridViewCheckBoxCell chk = row.Cells[0] as DataGridViewCheckBoxCell;

            isAllCheck = Convert.ToBoolean(chk.Value);
            if (!isAllCheck)
            {
                break;
            }
        }

        if (chkAllItem.Checked && !isAllCheck)
        {
            chkAllItem.Checked = false;
        }

        if (!chkAllItem.Checked && isAllCheck)
        {
            chkAllItem.Checked = true;
        }
    }
}

private void dataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (this.dataGridView.IsCurrentCellDirty)
    {
        this.dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

任何有关这些的提示都会有很大帮助。提前谢谢。

2 个答案:

答案 0 :(得分:1)

DataGridViewCheckBoxCell包含属性TrueValueFalseValueIndeterminateValue,其默认值为null。这些是属性Value给出的值,具体取决于复选框的状态。当Convert.ToBooleannull转换为false时,如果未初始化属性,则转化结果始终为false

这些可以在单元格本身或其拥有列上初始化。

因此,您需要将拥有列TrueValue初始化为true,将FalseValue初始化为false

答案 1 :(得分:1)

设置TrueValueFalseValueIndeterminateValue是个不错的开始。

我发现我还需要做更多工作;除了CurrentCellDirtyStateChanged事件,我还对这些事件进行了编码:

这会设置所有CheckBoxCells

private void cbx_all_CheckedChanged(object sender, EventArgs e)
{
    if (cbx_all.Tag == null) for (int i = 0; i < dataGridView.RowCount; i++)
    {
        dataGridView.Tag = "busy";
        dataGridView[yourCheckBoxcolumnIndex, i].Value = cbx_all.Checked;
        dataGridView.Tag = null;
    }
}

我对CellValueChanged而不是CellContentClick事件进行了编码:

private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == yourCheckBoxcolumnIndex &&  dataGridView.Tag == null)
    {
       cbx_all.Tag = "busy";
       cbx_all.Checked = testChecks(e.ColumnIndex);
       cbx_all.Tag = null;
    }
}

我使用Tag的{​​{1}}属性和DGV作为标记,我正忙于按代码更改值。其他一些避免无限循环的方法也同样合适。

这是测试功能:

CheckBox
相关问题