I'm pretty new to C# development, but here goes. I'm working on a plugin for Autodesk revit, which creates a windows form with a datagridview on it which gets populated with several checkbox columns when the form loads. What I would like to do is select multiple checkbox cells, and check one of the selected boxes in order to check all selected boxes.
I have tried using a SelectionChanged event handler to store the selected sells in another variable. Then I'm trying to use CellValueChanged in order to set all those cells to the new value
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;
}
}
My problem is that as soon as I click on the one cell, it resets the DataGridView.SelectedCells to that one cell and I lose the previous selection. Any help would be greatly appreciated!
EDIT: I solved this by storing the selection in another variable (selCells) and using a combination of the CellMouseUp, CellMouseDown, and CellValueChanged event handlers:
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();
}