Dong Lam Trien

Dong Lam Trien

  • 825
  • 986
  • 149.1k

Cross-thread operation not valid: Control 'gridControl'accessed from ?

Mar 13 2023 3:05 AM

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 ?


Answers (3)