Vladimír Paraska
Vladimír Paraska

Reputation: 47

DataGridView geting row index in c# gets exception out of range

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e){

menoDB = dataGridView1.Rows[idSelectedRow].Cells["meno"].Value.ToString();      
priezviskoDB = dataGridView1.Rows[idSelectedRow].Cells["priezvisko"].Value.ToString();       
kontaktDB = dataGridView1.Rows[idSelectedRow].Cells["kontakt"].Value.ToString();      
zaplatenetDB = dataGridView1.Rows[idSelectedRow].Cells["platene"].Value.ToString();
}

idSelectedRow = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["idludia"].Value.ToString());

It works perfectly in first 2 rows, but when I click on 3th it reads from 10th (the last one) after that when I click on 4th I get this exception.

System.ArgumentOutOfRangeException was unhandled

It is obvious it try to read from 11th row but there is no 11th row.

Upvotes: 1

Views: 927

Answers (1)

erikscandola
erikscandola

Reputation: 2936

The issue at this line:

idSelectedRow = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["idludia"].Value.ToString());

Now in your idSelectedRow you don't have the row index but idludia value. So change your code in this way:

menoDB = dataGridView1.Rows[e.RowIndex].Cells["meno"].Value.ToString();      
priezviskoDB = dataGridView1.Rows[e.RowIndex].Cells["priezvisko"].Value.ToString();       
kontaktDB = dataGridView1.Rows[e.RowIndex].Cells["kontakt"].Value.ToString();      
zaplatenetDB = dataGridView1.Rows[e.RowIndex].Cells["platene"].Value.ToString();

Upvotes: 2

Related Questions