17

CellContentClick event doesn't always work - it sometimes works and sometimes not, randomly.

My code is below, I am checking by using breakpoints but program sometimes enters the block and and some times not. Why is it so?

private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
    textBoxUserName.ReadOnly = true;
    button2.Visible = true;
    int index = e.RowIndex;
    if (!(index < 0))
    {
        DataGridViewRow row = dataGridView1.Rows[index];
        textBoxUserName.Text = row.Cells["UserNAme"].Value.ToString();
        textBoxPassword.Text = row.Cells["Pass"].Value.ToString();
        dataGridView1.Focus();
    }
    dataGridView1.Focus();
}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Muhammad Ali
  • 522
  • 2
  • 6
  • 18

2 Answers2

26

Try using the CellClick event instead:

Occurs when any part of a cell is clicked.

The CellContentClick event won't necessarily fire when you click in the cell, the user has to click into the "content" area of the cell, like the text, for instance:

Occurs when the content within a cell is clicked.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
0

Try using the CellClick event instead(As LarsTech said.).

Double click at the data grid on design view will link the CellContentClick event to a method, which means you need to click exactly the content, not the cell.

Say we have a cell named "IsChecked" which is a bool and displayed as a small check box. Clicking right in the check box will fire the CellContentClick while anywhere else will not.

"Anywhere else" includes spaces before and after contents, padding spaces, row headers.

When using CellClick instead, we need to check if the row header is clicked, which generating e.RowIndex = -1.

        if (e.RowIndex < 0 || e.RowIndex >= dataGridView.RowCount)
cheny
  • 2,545
  • 1
  • 24
  • 30