DataGridView:如何让一些单元格无法选择?

时间:2010-12-16 13:25:36

标签: c# winforms visual-studio-2010 datagridview

如何让DataGridView中的某些单元格无法选择?

“不可选择”是指:无法以任何方式进行选择,尝试选择它不会取消选择任何其他单元格。

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

DataGridView.MultiSelect必须是假的。

感谢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。我需要采取什么条件和地点来防止这种情况?

3 个答案:

答案 0 :(得分:15)

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

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

答案 1 :(得分:6)

您可以使用事件“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;
}

编辑:如果你将gridView的MultiSelect属性保留为True,你可以自己管理一个具有不可选择单元格的“单选”网格视图:il可以选择单元格,清除其他选择......

答案 2 :(得分:1)

我相信这篇文章可能对您有用:

http://blog.spencen.com/2009/04/25/readonly-rows-and-cells-in-a-datagrid.aspx

ReadOnly属性可以应用于整个网格,列,行或单个单元格。