scylla scylla - 1 month ago 16
C# Question

Passing data in hash table to a listbox in C# using "for loop"

I have been following this C# tutorial and found out that, it only describes to pass data in hash table to a list box using

foreach loop
.

I want to pass the data in my hash table using a
for loop
. Here's my code so far.

private void button1_Click(object sender, EventArgs e)
{
Hashtable students = new Hashtable();

students.Add("Peter", 67);
students.Add("Brayan", 76);
students.Add("Lincoln", 56);
students.Add("Jack", 65);
students.Add("Mahone", "no score");
students.Add("Kevin", 64);

for (int i = 0; i < students.Count; i++)
{
listBox1.Items.Add(students[i]);
}
}
}


}

enter image description here

Count method
in
for loop
works in
collections
. What's the right method for
for loop
when passing hash table data into a list box.

Answer

You should use a Dictionary instead of a HashTable, you should also use a foreach to make things easier, then you can do:

private void button1_Click(object sender, EventArgs e)
{
    Dictionary<string, int> students = new Dictionary<string, int>();

    students.Add("Peter", 67);
    students.Add("Brayan", 76);
    students.Add("Lincoln", 56);
    students.Add("Jack", 65);
    students.Add("Mahone", 0);
    students.Add("Kevin", 64);

    foreach (var student in students)
    {
        listBox1.Items.Add(student.Value);
    }
}

Note I replaced "no score" with 0 (thanks Viper)