How can I make some cells in DataGridView unselectable?
By 'unselectable' I mean: It cannot be selected in any way and trying to select it won't unselect any other cell.
I don't mean ReadOnly
. My cells already have this property as true.
DataGridView.MultiSelect
needs to be false.
Thanks to JYL's answer I wrote a code:
private int selectedCellRow = 0;
private int selectedCellColumn = 0;
private void grid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
if (e.Cell == null || e.StateChanged != DataGridViewElementStates.Selected)
return;
if (e.Cell.RowIndex == 0 || e.Cell.ColumnIndex == 0 || e.Cell.RowIndex == 1 && e.Cell.ColumnIndex == 1)
{
e.Cell.Selected = false;
grid.Rows[selectedCellRow].Cells[selectedCellColumn].Selected = true;
}
else
{
selectedCellRow = e.Cell.RowIndex;
selectedCellColumn = e.Cell.ColumnIndex;
}
//this was only for seeing what is happening
//this.Text = selectedCellRow + " " + selectedCellColumn;
}
But this leads to StackOverflow. What condition and where I need to put to prevent that?
Added and commented the condition you were asking about.
private int selectedCellRow = 0;
private int selectedCellColumn = 0;
private void grid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
if (e.Cell == null || e.StateChanged != DataGridViewElementStates.Selected)
return;
//if Cell that changed state is to be selected you don't need to process
//as event caused by 'unselectable' will select it again
if (e.Cell.RowIndex == selectedCellRow && e.Cell.ColumnIndex == selectedCellColumn)
return;
//this condition is necessary if you want to reset your DataGridView
if (!e.Cell.Selected)
return;
if (e.Cell.RowIndex == 0 || e.Cell.ColumnIndex == 0 || e.Cell.RowIndex == 1 && e.Cell.ColumnIndex == 1)
{
e.Cell.Selected = false;
grid.Rows[selectedCellRow].Cells[selectedCellColumn].Selected = true;
}
else
{
selectedCellRow = e.Cell.RowIndex;
selectedCellColumn = e.Cell.ColumnIndex;
}
}
You can use the event "CellStateChanged".
private void DataGridViewXYZ_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
if (e.Cell == null
|| e.StateChanged != DataGridViewElementStates.Selected)
return;
if (! [condition here : can this cell be selectable ?])
e.Cell.Selected = false;
}
EDIT : if you leave the MultiSelect property of gridView to True, you can manage yourself a "single select" gridview with unselectable cells : il the cell is selectable, clear the other selection...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With