如何将ProgressBar Control与DataGridView一起使用

时间:2014-07-03 10:31:18

标签: c# winforms datagridview progress-bar

我希望在我的ProgressBar加载数据时在C#中使用DataGridView控件,但是当我运行程序时出现错误:

  

跨线程操作无效:控制'dataGridView1'从其创建的线程以外的线程访问。

代码:

private readonly BackgroundWorker _bw = new BackgroundWorker();

public workerbloks()
{
    InitializeComponent();

    progressBar1.MarqueeAnimationSpeed = 30;

    // set Visible false before you start long running task
    progressBar1.Visible = false;
    _bw.DoWork += show_worked_bloks;
    _bw.RunWorkerCompleted += BW_RunWorkerCompleted;
}

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Show();
    _bw.RunWorkerAsync();
}

private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    progressBar1.Hide();
}

public void show_worked_bloks(object sender, DoWorkEventArgs doWorkEventArgs)
{
    MYDBMS md = new MYDBMS();
    DataTable dt = new DataTable();
    clsWorkBloks clswb = new clsWorkBloks();

    try
    {
        dt = md.ExecuteSelectSQL(clswb.show_all_worked_bloks());
        dataGridView1.DataSource = dt;
    }
    catch
    {
    }
}

1 个答案:

答案 0 :(得分:0)

在创建dataGridView1基础句柄的线程上异步执行指定的委托。

dataGridView1.BeginInvoke((MethodInvoker)delegate
{
    this.dataGridView1.DataSource = dt;
});

由于进度条只是选框显示。只需在运行后台工作人员之前将其带到前面。

progressBar1.BringToFront();
progressBar1.Show();
_bw.RunWorkerAsync();