Search code examples
c#datagridviewclickrowcell

On DataGridView CellDoubleClick Return Data From Another Row


My method:

private void dgvProveedores_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {

        _tbProveedorCodigo.Text = dgvProveedores.SelectedCells[0].Value.ToString();
        _tbProveedorNombre.Text = dgvProveedores.SelectedCells[1].Value.ToString();
        _indice.Text = dgvProveedores.SelectedCells[2].Value.ToString();
        _grid.Visible = false;
        this.Close();
    }

Row Example:

  CODE     Name     index
| 012 | AVIPECUARIA | 3 |

But Return:

| 012 | HECTOR JAVIER |214|

THIS DATA EXIST WITH THIS CODE:

| PM012 | HECTOR JAVIER |214|

This code works on all DB that i tested, but i found this issue on this.


Solution

  • Your code works with selected cells which can cause the issue. Try alternative solution and use 'e' argument property:

        private void dgvProveedores_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            _tbProveedorCodigo.Text = dgvProveedores.Rows[e.RowIndex].Cells["Codigo"].Value.ToString();
            _tbProveedorNombre.Text = dgvProveedores.Rows[e.RowIndex].Cells["Nombre"].Value.ToString();
            _indice.Text = dgvProveedores.Rows[e.RowIndex].Cells["Indice"].Value.ToString();
        }
    

    I used column names inside Cells brackets. You should use your column names. If there are null values in the grid cells it should be properly handled to avoid null reference exception.