I believe the line i = dataGridView1.SelectedCells[0].RowIndex; is throwing the exception.
instead try using
int i = datagridView1.CurrentCell.RowIndex;
or you can use
dataGridView1.SelectedRows[0].Cells[0] instead of dataGridView1.SelectedRows[i].Cells[0]