如何使用进度条控件与DataGridView

本文关键字:控件 DataGridView 何使用 | 更新日期: 2023-09-27 18:11:28

当我的DataGridView加载数据时,我想在c#中使用ProgressBar控件,但是当我运行我的程序时,我得到一个错误:

跨线程操作无效:控制'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
    {
    }
}

如何使用进度条控件与DataGridView

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

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

因为进度条只是字幕显示。简单地把它放在前面,然后再运行后台工作程序。

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