0

I want to bind my combobox's data source using a binding list. The binding list contains a collection of Client instances. I managed this and it works well, but because reading from the database takes long I decided to use a task. And now once the binding list is updated via the task the combobox still has no values.

I wanted to use a normal thread at first, but struggled so switched to using a task(pretty much the same thing I guess thing I guess). So a solution using threads would be just as useful.

    public partial class frmJobCreation : Form
    {
        public frmJobCreation()
        {
            InitializeComponent();
        }

        BindingList<Client> clients = new BindingList<Client>();

        private void frmJobCreation_Load(object sender, EventArgs e)
        {
            cbxRtojClient.DataSource = clients;
            Task.Run(() =>
            {
                clients = new BindingList<Client>(Client.GetClients());
            });
        }
    }

Where Client.GetClients() is a static method that returns List<Client>

Bharat Gupta
  • 2,628
  • 1
  • 19
  • 27
Storm Muller
  • 622
  • 6
  • 21

1 Answers1

1

In the form load event you have cbxRtojClient.DataSource = clients; and then you are updating the clients object in the Task. But this is never going to update the ComboBox.

A Task in C# (wrt winforms) should ideally perform a task and return its results so that it can be updated in the UI. The UI update should ideally be done in a ContinueWith continuation task which is run in the UI context. We should always update any control in the context of the UI thread. Check this for reference.

Task.Run<BindingList<Client>>(() =>
{
    // return all the clients to 'ContinueWith' task
    return new BindingList<Client>(Client.GetClients());
})
.ContinueWith(t =>
{
    // Result is a dynamic property and holds the output of its previous Task. BindingList<Client> in this case.
    clients = t.Result;

    // Update UI
    cbxRtojClient.DataSource = clients; 
}, TaskScheduler.FromCurrentSynchronizationContext()); // ensures calling the ContinueWith task to be run in the UI thread. 

To know more about Task Parallel Library (TPL) follow this.

Community
  • 1
  • 1
Bharat Gupta
  • 2,628
  • 1
  • 19
  • 27