user1667191
user1667191

Reputation: 2527

GUI/progress bar not updating from backgroundworker

I've been trying to get this work, but it just won't update anything on the GUI and my app exists on the error i showed in the code.

    ListViewItem item;

    public void SetStatusStrip()
    {
        BackgroundWorker bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;

        listviewTables.Columns.Add(gDatabase);

        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            try
            {
                MySqlCommand iCommand = new MySqlCommand("SHOW TABLES;", iCon);
                iRead = iCommand.ExecuteReader();
                int i = 0;
                while (iRead.Read())
                {
                    item = new ListViewItem(new[] { iRead.GetString(0) });
                    bw.ReportProgress(i);
                    i++;
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("There was an error getting tables from the database: " + gDatabase + ".\n\nError Dump:\n" + ex, "MySQL Error!");
                return;
            }
        });

        bw.ProgressChanged += new ProgressChangedEventHandler(
        delegate(object o, ProgressChangedEventArgs args)
        {
            progressBar1.Value = args.ProgressPercentage;
            listviewTables.Items.Add(item); // I get error here: System.ArgumentException
        });

        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        delegate(object o, RunWorkerCompletedEventArgs args)
        {
            progressBar1.Value = 0;

            // Finished.
        });

        bw.RunWorkerAsync();
    }

Upvotes: 1

Views: 111

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39122

I agree with LarsTech.

Pass out the ListViewItem in ReportProgress();

            while (iRead.Read())
            {
                bw.ReportProgress(i, new ListViewItem(new[] { iRead.GetString(0) }));
                i++;
            }

Then cast UserState in ProgressChanged() back to a ListViewItem:

    bw.ProgressChanged += new ProgressChangedEventHandler(
    delegate(object o, ProgressChangedEventArgs args)
    {
        progressBar1.Value = args.ProgressPercentage;
        listviewTables.Items.Add((ListViewItem)args.UserState);
    });

Note that I am NOT using your global var of "item", which is a bad idea to begin with.

Upvotes: 2

Related Questions