user1694527
user1694527

Reputation: 31

Add A list Items to Combobox using Dispatcher.BeginInvoke()

I want to add a List to ComboBox through Dispatcher.BeginInvoke. But when I try to put it in a loop, only last value is loading.

    private void LoadToComboBox(List<string> msg)
    {
        for (int i = 0; i < msg.Count; i++)
        {
           this.Dispatcher.BeginInvoke(() => cmbListItems.Items.Add(msg[i]));
        }
    }

Upvotes: 1

Views: 357

Answers (1)

tsiorn
tsiorn

Reputation: 2236

The Dispatcher.BeginInvoke() is an asynchronous call. What is happening is that by the time you are calling your cmbListItems.Items.Add() function, it is already set to msg.Count.

Try something like this:

private void LoadToComboBox(List<string> msg)
        {

            this.Dispatcher.BeginInvoke(() => 
            {
                for (int i = 0; i < msg.Count; i++) {
                    cmbListItems.Items.Add(msg[i]);
                }
            });

        } 

Upvotes: 2

Related Questions