title: How do I resolve index was out of range. Must be non-negative and less than the size of the collection. Error
body: <p>I am getting following exceptions in my code</p>
  
  <pre><code>Index was out of range. Must be non-negative and less than the size of the collection.
  Parameter name: index
  </code></pre>
  
  <p>I could not understand why it is throwing that exception.</p>
  
  <p>Flow of program is something like this : </p>
  
  <p>I have collection of number say 1 to 200. For each number in collections, it goes and run the below code. till 120, it did not throw the exception but for 121, its throwing the exception.  And it does randomly, if run the program again, I might get same exception for 123.</p>
  
  <p>What could be the reason? Is it something related with database connection? Is there any problem in my code? if so then should not it be throwing for the first iteration?</p>
  
  <p><strong>What I have tried:</strong></p>
  
  <pre><code>public DataTable GetGrade(DataTable dtReportTbl)
          {
              dtReportTbl.Columns.Add("Salary_Grade", typeof(System.String));
              dtReportTbl.Columns.Add("InsertedDate", typeof(DateTime));
              string query = "select Grade from student_grade where myTable in ('JMS','JSM') and  student_Num in ({StudentNums}) order by student_Num";
   
              try
              {
                  using (OracleConnection con = new OracleConnection(connectionString))
                  {
                      List&lt;string&gt; storeNums = new List&lt;string&gt;();
   
  
                      foreach (DataRow row in dtReportTbl.Rows)
                      {
                          storeNums.Add(row["store"].ToString());
                      }
   
                      var cmd = new OracleCommand(query, con);
   
                      // extension method to get StudentNums as to achieve cmd.Parameters.Add(new OracleParameter("pStudentNums", studentNum)
                      cmd.AddArrayParametersOra(storeNums, "StudentNums");
   
                      var rdr = cmd.ExecuteReader();
                      List&lt;string&gt; salGradelist = new List&lt;string&gt;();
                      while (rdr.Read())
                      {
                          salGradelist.Add(rdr["Grade"].ToString());
                      }
   
                      int i = 0;
                      foreach (DataRow row in dtReportTbl.Rows)
                      {
                          row["Grade"] = salGradelist[i];
                          row["RecordInsertedDate"] = DateTime.Today;
                          i++;
                      }
                  }
              }
              catch (Exception ex)
              {
                  throw;
              }
   
              return dtReportTbl;
          }
  </code></pre>