0
votes

Whenever a user clicks the row header, which selects the whole row (and highlights it blue), the cell in the first column is actually entered. That is, if you start typing stuff, the text goes in that cell. I want to prevent this. Would it be possible to have no datagridview cells being entered when one or many rows are selected?

I also need the solution to prevent cells being entered during multiple row selections caused by clicking and dragging on the row headers.

Any ideas on how I could achieve this?

Thanks

Isaac

3

3 Answers

2
votes

Set your DataGridView's ReadOnly property to true or false, depending on whether one or more rows have been selected or if the DGV's 'CellState' has changed.

Add the following two events for your DataGridView:

private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e) {
    if (e.StateChanged == DataGridViewElementStates.Selected) {
        Console.WriteLine("TRUE");
        dataGridView1.ReadOnly = true;
    }
}

private void dataGridView1_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e) {
    if (e.StateChanged == DataGridViewElementStates.Selected) {
        Console.WriteLine("false");
        dataGridView1.ReadOnly = false;
    }
}

This worked for me in my tests but I wouldn't be surprised if there were hidden 'gotchas.'

0
votes

An alternative solution may be something like this:

    private void dataGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0 && dataGrid.Rows[e.RowIndex].Selected)
            return;
    }
0
votes

Based on the answer of "Jay R" I adjusted the code a bit to not lose readonly flags of cells.

private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
    if (e.StateChanged == DataGridViewElementStates.Selected)
        e.Row.DataGridView.EditMode = DataGridViewEditMode.EditProgrammatically;
}

private void dataGridView1_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
    if (e.StateChanged == DataGridViewElementStates.Selected)
        // adjust the edit mode to your "default" edit mode if you have to
        e.Cell.DataGridView.EditMode = DataGridViewEditMode.EditOnEnter;
}