gpt4 book ai didi

c# - DataGridView:如何使某些单元格不可选择?

转载 作者:IT王子 更新时间:2023-10-29 04:43:49 29 4
gpt4 key购买 nike

如何使 DataGridView 中的某些单元格不可选择?

“不可选择”的意思是:无法以任何方式选择它并且尝试选择它不会取消选择任何其他单元格。

我不是说 ReadOnly。我的单元格已将此属性设置为 true。

DataGridView.MultiSelect 需要为 false。

感谢JYL的回答我写了一段代码:

    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;
}

但这会导致 StackOverflow。我需要在什么条件下放置什么位置才能防止这种情况发生?

最佳答案

添加并评论了您询问的条件。

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;
}
}

关于c# - DataGridView:如何使某些单元格不可选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4461181/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com