Cross-thread operation not valid: Control 'gridControl' accessed from a thread other than the thread it was created on.
string sPath = "";
private void cmdImportExcel1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Excel Files (.xls; .xlsx;)|*.xls; *.xlsx";
dlg.InitialDirectory = Environment.CurrentDirectory;
dlg.Title = "B?n ch?n file excel h?p d?ng...";
DialogResult dlgresult = dlg.ShowDialog();
if (dlgresult == DialogResult.OK)
{
if (!string.IsNullOrEmpty(dlg.FileName))
{
sPath = dlg.FileName;
Thread myThr = new Thread(ImportExcel1);
myThr.Start();//gridView1
}
}
}
private void ImportExcel1()
{
// Xóa các m?u tin trong table access
tmpSQL = "DELETE * FROM HDCNH;";
if (!clsConnecACS.ThucThiSQL(tmpSQL))
{
DevExpress.XtraEditors.XtraMessageBox.Show("L?i xóa table HDCNH không thành công !", "Thông báo !", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// Luu các m?u tin t? Excel vào Access
ExcelSaveTableAccess(1, sPath);
// Nhóm các m?u tin t? Table Access và luu vào gridView1
tmpSQL = "SELECT CHINHANH, HD, LOAIHANG, TIEUCHUAN, KHACHHANG, Sum(SOLUONG) AS SLUONG, DONGIA, (SLUONG*DONGIA) AS DOANHTHU,NGAYKY, LOAIHD, NGAYGIAO ";
tmpSQL += "FROM HDCNH ";
tmpSQL += "GROUP BY CHINHANH, HD, LOAIHANG, TIEUCHUAN, KHACHHANG, DONGIA, NGAYKY, LOAIHD, NGAYGIAO ";
tmpSQL += "ORDER BY HD;";
Debug.Print(tmpSQL);
//Cross-thread operation not valid: Control 'gridControl' accessed from a thread other than the thread it was created on.
gridControl1.DataSource = clsConnecACS.FillDatatable(tmpSQL);//Error here
Format_Gridview(gridView1);
}
How to fix this error ?
Dong Lam TrienPosted Mar 14, 2023, 1:36 AM
Hello Jignesh Kumar ! If I write code that doesn't use threads, my program runs fine, but if the excel file has more than 1000 records when it is loaded on the computer, it freezes a little and then goes back to normal, so I want to use thread to solve the problem. for the computer to run smoother when loading data is an excel file, otherwise the excel file has less than 500 records when loaded on a normal computer.
Hello Amit Mohanty ! Can you rewrite the above code to remove LINQ ?
Amit MohantyPosted Mar 13, 2023, 4:04 AM
Try this
Jignesh KumarPosted Mar 13, 2023, 3:43 AM
Hello,
Why are you using thread here any specific reason for that ?