Error: "Cross-thread operation not valid" Problem here

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ahmedhussain
    New Member
    • Dec 2008
    • 79

    Error: "Cross-thread operation not valid" Problem here

    hey everyone...
    I have a code which gives me this error.

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

    I am actually populating a user control dynamically. And the problem arises when i try to populate it with values. and the code runs again after 30 or more seconds to get updated values and so on..

    The code is given below
    This is actually the user control which should be pupulated dynamically and provide values according to the query...This user control is known as view
    Code:
     private List<string> getData(string sensorID)
            {
                cmdText = "SELECT ID, SensorID, Temperature, Humidity, Light, SoilMoisture, ReceivingDateTime " +
                          " FROM SensorValues SV" + " where SV.ID in (SELECT max(ID) From SensorValues WHERE SensorID LIKE '" + sensorID + "')";
                sqlCon = new SqlConnection(sqlString);
                sqlCom = new SqlCommand(cmdText, sqlCon);
    
                try
                {
                    sqlCon.Open();
                    rd = sqlCom.ExecuteReader();
                    while (rd.Read())
                    {
                        values.Add(rd["SensorID"].ToString());
                        values.Add(rd["Temperature"].ToString());
                        values.Add(rd["Humidity"].ToString());
                        values.Add(rd["Light"].ToString());
                        values.Add(rd["SoilMoisture"].ToString());
                        values.Add(rd["ReceivingDateTime"].ToString());
                    }
                    rd.Close();
    
                }
                catch (Exception args)
                {
                    MessageBox.Show("Error : " + args);
                }
                finally
                {
                    sqlCon.Close();
                }
                return values;
    
            }
    the problem arises in the following function when called.
    Code:
            public void setValues(string sensorID)
            {
                values = this.getData(sensorID);
                textBox1.Text = values[0];
                textBox2.Text = values[1];
                textBox3.Text = values[2];
                textBox4.Text = values[3];
                textBox5.Text = values[4];
                textBox6.Text = values[5];
            }
    And the below is the given class which calls the above usercontrol called view.
    Code:
    List<View> L = new List<View>();
            
            View V;
            public static int total = 7;
            public static String[] SensorIDs = new String[] { "01F4", "0001", "0002", "0003", "0004", "0005", "0006" };
            Terminal T = new Terminal();
            
            public AdminUserControl1()
            {
                InitializeComponent();
                //panel2.Visible = false;
                this.Load += new EventHandler(AdminUserControl1_Load);
            }
    
            void AdminUserControl1_Load(object sender, EventArgs e)
            {
    /*View usercontrol is populated in this function*/
    
                double hMaxBy2 = (double)1024 / 2;
                double yMaxBy3 = (double)768/3;
    
                int x=0,y=0;
    
                for (int i = 1; i <= total; i++)
                {
    
    
                    if (i == 3 || i == 5 || i == 9)
                    {
                        x = 0;
                        y++;
                    }
                    if (i == 7)
                    {
                        x = 0;
                        y = 0;
                    }
    
                    V = new View();
    
                    V.Show();
                    V.SetBounds((int)(x * hMaxBy2), (int)(y * yMaxBy3), (int)hMaxBy2, (int)yMaxBy3);
                    splitContainer1.Panel2.Controls.Add(V);
                    L.Add(V);
                    x++;
                }
                
                splitContainer1.Visible = true;
            }
    
    
            private void dataFillerOpenToolStripMenuItem_Click(object sender, EventArgs e)
            {
                System.Timers.Timer Clock = new System.Timers.Timer();
                Clock.Interval = 25000;
    
                Clock.Elapsed += new System.Timers.ElapsedEventHandler(Clock_Elapsed);
    
                Clock.Start();
                
            }
    
            void Clock_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                Filler startFiller = new Filler();
                ThreadStarter cs = new ThreadStarter();
                ThreadStarter.main(null);
    
                for (int i = 0; i < 7; i++)
                {
                    
                    L[i].setValues(SensorIDs[i]);
                }
                
              
            }
    
        }    
    }
    If any one can help.

    Thank you,

    Regards,
    Syed Ahmed Hussain
  • MrMancunian
    Recognized Expert Contributor
    • Jul 2008
    • 569

    #2
    Did you set breakpoints to see at what point you get the error message? If not, please do so and tell us which line gives you the error.

    Steven
    Last edited by MrMancunian; Aug 3 '09, 10:29 AM. Reason: Typo

    Comment

    • Ahmedhussain
      New Member
      • Dec 2008
      • 79

      #3
      Yes I did set up the break points .... It gave me an error on the following line. :

      Code:
      textBox1.Text = values[0];

      Comment

      • Ahmedhussain
        New Member
        • Dec 2008
        • 79

        #4
        I dont know how but when I called the function it got 12 values in it as well..

        regards,
        Syed Ahmed Hussain

        Comment

        • tlhintoq
          Recognized Expert Specialist
          • Mar 2008
          • 3532

          #5
          Error : Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.
          You created the textbox on one thread... and are now trying to change its values on another thread. You can't do that.

          Take a look at Method Invoker. You can create an invoker (which works across thread barriers) which will invoke your control's add method to add your values.

          Comment

          • Ahmedhussain
            New Member
            • Dec 2008
            • 79

            #6
            You can create an invoker (which works across thread barriers) which will invoke your control's add method to add your values.
            Please provide me an example

            Thank you,

            Regards,
            Syed Ahmed Hussain

            Comment

            • tlhintoq
              Recognized Expert Specialist
              • Mar 2008
              • 3532

              #7
              Please provide me an example
              Take a look at the MSDN for method invoker.
              If after giving it a try on your own it still doesn't work, post the code you have created/tried and we'll see if we can't find where you went wrong.

              Comment

              • Ahmedhussain
                New Member
                • Dec 2008
                • 79

                #8
                Error: " Exception has been thrown by the target of an invocation." at program.cs
                on line :
                Code:
                Application.Run(new Startup());

                Comment

                • Ahmedhussain
                  New Member
                  • Dec 2008
                  • 79

                  #9
                  I have done this..
                  Code:
                    public delegate void MethodInvoker();
                          public void setValues(string sensorID)
                          {
                              MethodInvoker invoker1 = new MethodInvoker(delegate()
                              {
                                  values = this.getData(sensorID);
                                  textBox1.Text = values[0];
                                  textBox2.Text = values[1];
                                  textBox3.Text = values[2];
                                  textBox4.Text = values[3];
                                  textBox5.Text = values[4];
                                  textBox6.Text = values[5];
                              }
                              );
                              this.BeginInvoke(invoker1);
                          }
                  and I am getting the error : "{"Index was out of range. Must be non-negative and less than the size of the collection.\r\n Parameter name: index"}"

                  Comment

                  • MrMancunian
                    Recognized Expert Contributor
                    • Jul 2008
                    • 569

                    #10
                    Sounds like you forgot to subtract 1 from a collection...Co llections start at 0.

                    Steven

                    Comment

                    • Ahmedhussain
                      New Member
                      • Dec 2008
                      • 79

                      #11
                      @MrMancunian :

                      Thanks buddy. But I found the problem. The problem lies in the database as well. Their wasnt any value with the name of the parameter that was given to it.
                      Then I realize that there should be a condition of count to work with. If there is a count then it will simply map the values, else it wont.

                      Thank you every one.

                      :)

                      Regards,

                      Syed Ahmed Hussain

                      Comment

                      • MrMancunian
                        Recognized Expert Contributor
                        • Jul 2008
                        • 569

                        #12
                        Originally posted by Ahmedhussain
                        @MrMancunian :

                        Thanks buddy.
                        //Offtopic: Woohoo! I'm someone's buddy! :-D

                        //Ontopic: Good job :-)

                        Comment

                        Working...