Results 1 to 19 of 19

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

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

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

    Cross-thread operation not valid: Control 'gridControl' accessed from a thread other than the thread it was created on.

    Code:
    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 đồ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;
                }
    
                // Lưu các mẫu tin từ Excel vào Access
                ExcelSaveTableAccess(1, sPath);
    
                // Nhóm các mẫu tin từ Table Access và lưu 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 ?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    What exactly is confusing you here? You deliberately start a new thread so why are you surprised that your code is executed on a different thread? You can't touch the UI except on the UI thread.

    If you don't want to get into Tasks and async/await, one easy option would be to use a BackgroundWorker, do the data retrieval in the DoWork event handler (it's executed on a secondary thread) and then update the UI in the RunWorkerCompleted event handler (it's executed on the UI thread).

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    Hello jmcilhinney ! 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.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    I didn't tell you not to use a second thread. I said that, if you are using a second thread, then why are you surprised that you're getting an error message telling you that your code is executed in a second thread. You cannot touch the UI in the second thread. It's pretty simple stuff. The UI thread is called the UI thread for a reason. Anything you do to the UI must be done on that thread. You're setting the DataSource of gridControl1. That's the UI. I've told you how to solve the problem. All you have to do is what I said.

  5. #5

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    I understand your problem, but I don't know how to write syntax use Thread for Devexpress girdView1, I'm searching on google.com but haven't found the syntax when assigning gridControl1.DataSource = FillDatatable(tmpSQL) Thread

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    I told you what to do: use a BackgroundWorker instead of creating a Thread explicitly. The BackgroundWorker class exists specifically to make scenarios like this simple.

  7. #7

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    Previously, I knew when writing computer programs that it would hang or freeze, operate unstable in parallel with data, use more Thread to solve the problem, now you tell me more about using "BackgroundWorker" ". I don't know about this "BackgroundWorker" technique, I want to find this example, to learn this technique on google is the keyword "BackgroundWorker", right ?

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth


  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    For the record, if you wanted to stick with creating your own Thread, you can marshal a method call to the UI thread using the technique provided here:

    https://www.vbforums.com/showthread....Worker-Threads

  10. #10

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    In your opinion, writing code in "BackgroundWorker" style and writing code in "Thread" style is simpler and easier to use? I tried writing code in "Thread" style when reading the table, opening the table got an error, I can't float, you see the error code when using Thread, if you remove Thread, the code runs fine
    Code:
    //1: The connection was not closed. The connection's current state is connecting.
    //2: An attempt has been made to free an RCW that is in use.  The RCW is in use on the active thread or another thread.  Attempting to free an in-use RCW can cause corruption or data loss.
    if (objConnect.State != System.Data.ConnectionState.Open)
                {
                    objConnect.Open();        Error 1
                }
                OleDbCommand cmd = new OleDbCommand(sSQL, objConnect);
                try
                {
                    cmd.ExecuteNonQuery();
                    objConnect.Close();          //Error 2
                    return true;
                }
                catch (OleDbException ex)
                {
                    objConnect.Close();                
                    return false;
                }
    
    
    //3: The connection was not closed. The connection's current state is connecting.
    OleDbCommand cmd = new OleDbCommand(tmpSQL, clsConnecACS.objConnect);
                    try
                    {
                        cmd.Parameters.AddWithValue("@HD", dtExcel.Rows[i]["HD"].ToString());                  
                        cmd.Parameters.AddWithValue("@SOLUONG", dtExcel.Rows[i]["SOLUONG"]);
                        cmd.Parameters.AddWithValue("@DONGIA", dtExcel.Rows[i]["DONGIA"]);
    
    
                        if (clsConnecACS.objConnect.State != System.Data.ConnectionState.Open)
                        {
                            clsConnecACS.objConnect.Open();
                        }
                        cmd.CommandType = CommandType.Text;
                        cmd.ExecuteNonQuery();                    Error 3
    
                        // Đóng kết nối database
                        clsConnecACS.objConnect.Close();
                    }
                    catch (OleDbException ex)
                    {
                        clsConnecACS.objConnect.Close();                    
                    }

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    Originally, you only had the Thread and ThreadPool classes. Later, they provided the BackgroundWorker to use in GUI applications to simplify performing background work and updating the UI. There is also the SynchronizationContext class to be used in non-GUI code to ensure UI-specific work is done on the UI thread. Most recently, they have provided Tasks and Async/Await. If you don't want to learn about the latter, you should use the BackgroundWorker in a GUI app in most cases.

    The problem with your most recent code is that your DAL is garbage. I see a lot of people try to create a DAL but it's so half-assed that it does more harm than good. Whether you do your data access in your forms or a dedicated DAL, you should be creating new connection objects as needed, not having a single connection object and checking whether it's open all the time. Create, open, use and destroy as required. Stick to that and you won't have these issues.

    For the record, words like "garbage" and "half-assed" may sound insulting but they are not intended to be. I've done plenty of garbage and half-assed stuff myself. It's just a matter of recognising it when you learn something new and making the appropriate changes where and when you can.

  12. #12

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    Both of the examples you sent I did not find an example of read, write, delete, update the table for access data, I searched on google without a demo, for example, ... so how to write "Thread" and "BackgroundWorker" is hard to do

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    Good lord! Of course there's no example of data access because that's not what those threads are about. Use your head. The point is that you do the time-consuming work, WHATEVER THAT MAY BE, in the background thread and then you update the UI on the UI thread. I've provided you with two different ways to do that. Just do it already. If the background work is read data from a database then do that. That's got nothing to do with multi-threading. I'm done here because I just can't keep repeating myself every time you try to make something complicated out of something simple. After all this I've still seen no attempt from you to write any code using a BackgorundWorker or an Invoke method so what's the point?

  14. #14
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    Here's one final effort. This is exactly what I've already told you to do multiple times:
    csharp Code:
    1. private void button1_Click(object sender, EventArgs e)
    2. {
    3.     backgroundWorker1.RunWorkerAsync();
    4. }
    5.  
    6. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    7. {
    8.     var table = new DataTable();
    9.  
    10.     using (var connection = new SqlConnection("connection string here"))
    11.     using (var command = new SqlCommand("SELECT * FROM Table1", connection))
    12.     {
    13.         connection.Open();
    14.  
    15.         using (var reader = command.ExecuteReader())
    16.         {
    17.             table.Load(reader);
    18.         }
    19.     }
    20.  
    21.     e.Result = table;
    22. }
    23.  
    24. private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    25. {
    26.     var table = (DataTable)e.Result;
    27.  
    28.     bindingSource1.DataSource = table;
    29.     dataGridView1.DataSource = bindingSource1;
    30. }
    There's nothing out of the ordinary there. It's basic data access and exactly what I've already showed you of a BackgroundWorker. Now I'm done.

  15. #15

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    using backgroundWorker when running the program no longer hangs, freezes,... but I want to insert each record into gridView1 when running, why doesn't it work ? I'm reviewing this place
    Code:
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    MessageBox.Show("Error: " + e.Error.Message);
                }
                else
                {
                    gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.True;
    
                    DataTable tmpdt = (DataTable)e.Result;
                    for (int i = 0; i < tmpdt.Rows.Count; i++)
                    {
                        try //nếu gặp tất các lỗi gán dữ liệu,... 
                        {
                            gridView1.AddNewRow();
                            gridView1.IsNewItemRow(i);
                            
                            gridView1.SetRowCellValue(i, gridView1.Columns["HD"], tmpdt.Rows[0]["HD"].ToString());                        
                            gridView1.SetRowCellValue(i, gridView1.Columns["SLUONG"], tmpdt.Rows[0]["SLUONG"].ToString());
                            gridView1.SetRowCellValue(i, gridView1.Columns["DONGIA"], tmpdt.Rows[0]["DONGIA"].ToString());
                            
                            gridView1.UpdateCurrentRow();
                            
                        }
                        catch
                        {
                            //
                        }
                    }
    
                    //gridControl1.DataSource = (DataTable)e.Result;                
                }
            }

  16. #16
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    Quote Originally Posted by dong View Post
    using backgroundWorker when running the program no longer hangs, freezes
    Then your problem is solved.
    Quote Originally Posted by dong View Post
    I want to insert each record into gridView1 when running
    That's not what you showed in the first place, so you've now solved the problem you asked about and are asking a completely new question. You need to mark this thread Resolved and create a new thread that provides ALL and ONLY the information relevant to the new issue.

  17. #17

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    I can this topic, you have added "BackgorundWorker" running in the background, so there are 2 ways: "Thread" and "BackgorundWorker". Writing style "BackgorundWorker" is simple and easy to use, but when running, I want to display on the gridView1 interface, adding each record can not be displayed, so the second way is "Thread", writing "Thread" is very difficult, I think this will solve the problem of running in the background and displaying each gridView1 record at runtime.

  18. #18
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    If you had bothered to follow link I provided in post #8 and read that thread then you'd already have you're answer. This is different question and it's already been answered. I'm out.

  19. #19

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    517

    Re: Cross-thread operation not valid: Control 'gridControl'accessed from a thread oth

    Thank you for answering my question

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width