0
votes

I need to allow the user to select a row by clicking on the row header to allow row deletion, but when the row header is clicked, the first cell gets focus and the text is highlighted, which I need to prevent so the user can't make accidental edits to that first cell.

Here's an example of what's happening: DGV Row Selected

As you can see, the first cell has focus and the user can edit that cell, when all that was done was the row header was clicked.

I tried the answer to this SO question, but neither event fired when I clicked a row header. Here's the code that I used for that attempt:

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

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

I also tried experimenting with the various DataGridViewEditMode options, but none of those accomplished what I need.

The DGV SelectionMode is set to RowHeaderSelect.

I still need to be able to grab the hidden "id" field in the row for the delete process. Here's my code for that:

private void btnDeleteRow_Click(object sender, EventArgs e)
{
    int index = dgvCategories.SelectedRows[0].Index;
    string rowId = dgvCategories[0, index].Value.ToString();

    string deleteString = string.Format("DELETE FROM masterfiles.xref WHERE id = " + rowId);

    conn.Open();
    NpgsqlCommand deleteCmd = new NpgsqlCommand(deleteString, conn);
    deleteCmd.ExecuteNonQuery();
    conn.Close();
}

That works; I just need to prevent that first cell from automatically getting focus for editing when the row is selected. I still need to allow the user to select individual cells for editing, as well.

1
I believe that you have dgvCategories.EditMode = DataGridViewEditMode.EditOnEnter;, so setting this to DataGridViewEditMode.EditOnKeystroke or DataGridViewEditMode.EditOnKeystrokeOrF2 will do.user10216583
@JQSOFT - That did the trick, Thanks.marky
@JohnG - Nothing was preventing me from doing that, I just mentioned it in case a fix was suggested that might affect/prevent that need.marky

1 Answers

0
votes

Try :
1- make the DataGridView selection by one row instead of one cell .
2- Disable allowing user to edit the DataGridView.
3- Make DataGridView ReadOnly .
Do 1 & 2 all the time except at editing operation .