Question

I want to list all objects in my ScoresList to a list box.

private void UpdateStudentScores_Load(object sender, EventArgs e)
{
    students.Fill();
    txtName.Text = students[index].WholeName;
    lstScores.Items.Clear();
    int s = 0;
    for (int i = 0; i < students[index].ScoresList.Count; i++)
        s = students[index].ScoresList[i];
        lstScores.Items.Add(s);
}

I want to be adding "s" to my list four times because the students[index].ScoresList.Count = 4. Instead I only get the last element in my list displayed. Where did I go wrong?

Was it helpful?

Solution

You need this:

lstScores.Items.Add(students[index].ScoresList[i]);

Or the curly braces:

for (int i = 0; i < students[index].ScoresList.Count; i++)
{
    s = students[index].ScoresList[i];
    lstScores.Items.Add(s);     
}

If you have more than one line in the body of your loop use curly braces. Your loop run four times but only add your last item because s become equal to last item after the loop.When you don't use curly-braces only the first line that comes after the loop considered as loop body.So lstScores.Items.Add(s); executing after the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top