【问题标题】:How to use ProgressBar Control with DataGridView如何将 ProgressBar 控件与 DataGridView 一起使用
【发布时间】:2014-07-03 10:31:18
【问题描述】:

当我的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
    {
    }
}

【问题讨论】:

  • 对 DataGridView1 使用 BeginInvokedataGridView1.Invoke
  • 你能用调用对象验证我的代码吗?
  • 你试过给出答案吗?
  • MSDN上查看后台工作人员的演练;特别注意报告进度功能!

标签: c# winforms datagridview progress-bar


【解决方案1】:

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

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

由于进度条只是选框显示。只需在运行后台工作程序之前将其置于前面。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多