title: How can I solve an index out of range error?
body: <p>I hava a combo box that contains students from a studentList. When I select a student it should populate a text field of the students name. Whenever a student is selected from the combo box I get the following error</p>
  
  <pre><code>ArgumentOutOfRangeException was unhandled
  Index was out of range. Must be non-negative and less than the size of the collection.
  </code></pre>
  
  <p>I think the problem may be in my loop but I'm having trouble finding out how to fix the error, any help would be appreciated </p>
  
  <pre><code>private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  {
      int i;
      for (i = 0; i &lt; Main.studentList.Count; i++)
      {
          if (comboBox1.SelectedItem == Main.studentList[i].StudentName + " " + Main.studentList[i].StudentId)
          {                  
              break;
          }
      }
  
      txtName.Text = Main.studentList[i].StudentName; //where the error occurs
  }
  
  public void ChangeStudent_Load(object sender, EventArgs e)
  {
      //loading combobox from studentList
      foreach (var student in Main.studentList)
      {
          comboBox1.Items.Add(student.StudentName + " " + student.StudentId);
      }
  }
  </code></pre>