you have set
dataGridView5.RowCount = 2;
but you access 3rd row in that error line
dataGridView5.Rows[2]
, this is zero based index, so 2nd index means 3rd item. if you need 2nd item you change it as
dataGridView5.Rows[1]
next error can occur when you access
dataGridView3.Rows[k]
, in line 15 you are increasing k value, it can be increase more than the existing rows of
dataGridView3
, you may need to put validation.
if (k >= dataGridView3.RowCount)
break;
dataGridView5.Rows[1].Cells[i].Value = dataGridView3.Rows[k].Cells[L + p].Value;