在C#datagridview中选中一个时如何检查所有选中的复选框

时间:2019-01-18 15:08:10

标签: c# datagridview multi-select revit-api

我对C#开发还很陌生,但是可以。我正在为Autodesk revit制作一个插件,该插件创建一个带有datagridview的Windows窗体,该窗体在加载时会填充多个复选框列。我想做的是选中多个复选框单元格,然后选中其中一个复选框以选中所有选中的复选框。

我尝试使用SelectionChanged事件处理程序将选定的卖出存储在另一个变量中。然后,我尝试使用CellValueChanged来将所有这些单元格设置为新值

    DataGridViewSelectedCellCollection selCells = null;
    private void revDataGridView_SelectionChanged(object sender, EventArgs e)
    {
        selCells = revDataGridView.SelectedCells;
    }

    private void revDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        foreach(DataGridViewCell cell in selCells)
        {
            cell.Value = revDataGridView[e.ColumnIndex, e.RowIndex].Value;
        }
    }

我的问题是,当我单击一个单元格时,它将DataGridView.SelectedCells重置为该单元格,而我又失去了先前的选择。任何帮助将不胜感激!

编辑:我通过将选择存储在另一个变量(selCells)中并结合使用CellMouseUp,CellMouseDown和CellValueChanged事件处理程序来解决此问题:

private void revDataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (selCells != null && selCells.Count>1)
        {
            revDataGridView.EndEdit();
            selCells = revDataGridView.SelectedCells; 
        }
        else if(selCells !=null && selCells.Count == 1)
        {
            selCells = revDataGridView.SelectedCells;
            revDataGridView.EndEdit();
        }
    }
    //when a value is changed, apply change to all selected cells
    private void revDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        foreach(DataGridViewCell cell in selCells)
        {
            if (cell.ReadOnly == false)
            {
                cell.Value = revDataGridView[e.ColumnIndex, e.RowIndex].Value;
                cell.Selected = true; 
            }
        }
    }
    //clear selection upon mouse button down
    private void revDataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        revDataGridView.ClearSelection();
    }

0 个答案:

没有答案