简体   繁体   中英

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'

This error is appearing when it reaches the classes[0].AddLesson(one); line and I have no idea why this is happening? any ideas would be great... I have two classes btw Lesson and Timetable

   List<Timetable> classes = new List<Timetable>();
    private void Form1_Load(object sender, EventArgs e)
    {
        
        Lesson one = new Lesson("maths", 1, 2);
        Lesson two = new Lesson("science", 3, 4);
        classes[0].AddLesson(one);
        classes[1].AddLesson(two);

        DisplayList(classes);

    }

    void DisplayList(List<Timetable> timetable)
    {
        lstTimetable.Items.Clear();
        foreach(Timetable t in timetable)
        {
            lstTimetable.Items.Add(t);
        }
    }

The list is empty, so you first have to assign values to the list. If you replace

classes[0].AddLesson(one);

with

classes.Add(one);

It should work.

Source

You have created a new list here:

List<Timetable> classes = new List<Timetable>();

But you haven't added anything to that list so it had no length (zero indexes). When you try to assign a value to the first index of the list here:

classes[0].AddLesson(one);

You're getting the exception because index 0 doesn't exist.

If you want to add to a list you do:

classes.Add(one);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM