简体   繁体   中英

How can I stop cells from being entered when a datagridview row is selected by a row header click?

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

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.'

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM