greatmajestics
greatmajestics

Reputation: 1093

Combo Box Update in c#

I am working on combo box, i am refresh the combo box values , first i am deleting all values and then re populating it. But it is not working. The code duplicates the values in combo box which is creating problem. Here is my Code.

    for (int i = 0; i < updateCombo.Items.Count; i++)
    updateCombo.Items.RemoveAt(i);

    //----------- Now Adding New Values --------
    updateCombo.Items.Add("Select an option . . .");

    SqlCommand command = new SqlCommand(Queries.qry9, connection);
    SqlDataReader reader = command.ExecuteReader();

Kindly please help me in fixing this problem.

Upvotes: 0

Views: 480

Answers (2)

Jon Collins
Jon Collins

Reputation: 193

Your for loop is deleting the item at 0, then at 1, then at 2, and so on. However, when the item at 0 is deleted, that position in the list doesn't remain empty - the other items effectively shift down by one.

So, if you changed your clearing code to:

for (int i = 0; i < updateCombo.Items.Count; i++)
updateCombo.Items.RemoveAt(0);

it should work. However, as others have suggested, using updateCombo.Items.Clear(); is a better approach.

Upvotes: 1

Code Uniquely
Code Uniquely

Reputation: 6373

Not sure why this would happen- but if Items.Count comes back as 0 then your loop won't remove any of the existing contents from the items list and you'll get duplicates.

have you tried just clearing all the contents of the list regardless using:

updateCombo.Items.Clear(); 

It saves you having to iterate through them all, removing them one by one anyway.

Upvotes: 3

Related Questions