0

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?

1
  • Type Ctrl-E Ctrl-D in Visual Studio's code editor and you will see... Commented Mar 8, 2014 at 22:02

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.