Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
115
Converting for loop to a foreach
posted

Hello all! I am wondering how you would change this for loop to a foreach? I am getting index errors and everything else.

 int rowIndex = dgvBudget.Rows.Count;
        for (int i = 0; i < rowIndex; i++)
        {
            var row = dgvBudget.Rows[i];
            row.Cells["Actual_c"].Value = lastki[i];
			row.Cells["PrevFY"].Value = lastkiBudget[i];
        }

I have heard it's smarter and more efficient to use foreach so I would like to be able to use this now and in the future. thank you.

Parents
No Data
Reply
  • 28925
    Offline posted

    Hello Blake, 

    Where are you getting an out of range exception? A for each loop may not necessarily benefit you if you are still iterating over the same elements. Look like you will need to do some error handling and make sure elements such as lastki, lastkiBudget and rows collection are not null or empty. 

Children
No Data