在c# winforms应用程序中,我有两个日期的datagridview开始日期和结束日期。我需要在日期范围内填充datagridview。它需要很多时间来填充datagridview和windows窗体exe变得没有响应。我现在使用后台工作程序。它填充datagridview当我点击搜索按钮后,选择日期。我点击清除按钮清空datagridview。当我再次选择日期并单击搜索按钮时,我得到了错误。
跨线程操作无效控件从创建它的线程以外的线程访问。
private clsStkBAL obj = new clsStkBAL();
public frmSalesStk()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
}
private void FillGrid()
{
try
{
this.obj.SP_STATUS = nameof(FillGrid);//SP_SalesInvoice
this.obj.Sih_StartDate = new DateTime?(this.dtpFromdt.Value.Date);//set_Sih_StartDate
this.obj.Sih_EndDate = new DateTime?(this.dtpToDate.Value.Date);
clsCommon.BindeDataGridView(this.dgvStock, (object)this.obj.GetDataTable((clsSalesStock)this.obj, (SqlTransaction)null, false), false);
// ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
}
catch (Exception ex)
{
clsCommon.ShowErrorMessage(ex.Message);
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
if(backgroundWorker1.IsBusy)
{
clear();
}
backgroundWorker1.RunWorkerAsync(2000);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (btnSearch.InvokeRequired)
{
dgvStock.Invoke(new Action(FillGrid));
}
FillGrid();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (backgroundWorker1.IsBusy)
{
Thread.Sleep(20000);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Loaded");
backgroundWorker1.Dispose();
dtpFromdt.Enabled = true;
dtpToDate.Enabled = true;
}
private void frmSalesStock_Load(object sender, EventArgs e)
{
dtpFromdt.Value = new DateTime(2021, 02, 01);
dtpToDate.Value = new DateTime(2021, 02, 01);
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
}
public void clear()
{
dgvStock.DataSource = null;
backgroundWorker1.CancelAsync();
}
private void btnClear1_Click(object sender, EventArgs e)
{
clear();
}
}
how to fix this error.pls
如何修复此错误。
1条答案
按热度按时间svdrlsy41#
我觉得这句话有点不靠谱:
这个错误是因为你应该在主线程上处理UI的事情:
跨线程操作无效控件从创建它的线程以外的线程访问。
看起来你在后台工作者中调用Action,这有问题--在主线程外执行--这是我写的一个例子,你可以使用CodeConverter将它从VB.Net移植回C#:
https://stackoverflow.com/a/13486676/495455