1

我一直在尝试完成这项工作,但它不会更新 GUI 上的任何内容,并且我的应用程序存在于我在代码中显示的错误中。

    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();
    }
4

1 回答 1

2

我同意 LarsTech。

在 ReportProgress() 中传递 ListViewItem;

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

然后将UserStateProgressChanged() 转换回 ListViewItem:

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

请注意,我没有使用“item”的全局变量,这是一个坏主意。

于 2013-10-25T22:01:30.677 回答