[英]How to use ProgressBar Control with DataGridView
I want to use a ProgressBar
control in C# when my DataGridView
is loading data, but when I run my program I get an error: 我想在
DataGridView
加载数据时在C#中使用ProgressBar
控件,但是在运行程序时出现错误:
Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
跨线程操作无效:控件“ dataGridView1”从创建该线程的线程之外的线程访问。
Code: 码:
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
{
}
}
Execute the specified delegate asynchronously on the thread that the dataGridView1
underlying handle was created on. 在创建
dataGridView1
基础句柄的线程上异步执行指定的委托。
dataGridView1.BeginInvoke((MethodInvoker)delegate
{
this.dataGridView1.DataSource = dt;
});
As the progressbar is just marquee display. 由于进度条只是字幕显示。 Simply bring it to front before running background worker.
只需在运行后台工作者之前将其放在最前面即可。
progressBar1.BringToFront();
progressBar1.Show();
_bw.RunWorkerAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.