Question

I am trying to get value out of datagridview on mouse click event.

Works great until I click on headers in datagridview. I get an error saying:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name:index

I use this code to detect mouse click:

 private void dataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dataGridView1.Rows[e.RowIndex].Index != -1)
            {
                textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            }
            else
            {
                textBox1.Text = "";
            }
        }

"dataGridView1.Rows[e.RowIndex].Index != -1" doesn't work and I do not know why.

Any easy solution to disable mouse click event on headers would be great! Thanks!

I also use:

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

to select whole column and CellContentClick doesn't work. If I am lucky, CEllContentClick works 3/10 times.

Was it helpful?

Solution

Try writing this instead:

private void dataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.RowIndex != -1)
    {
        textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
    }
    else
    {
        textBox1.Text = "";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top