简体   繁体   中英

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.

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.

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.

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