473,772 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

79 New Member
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
Expand|Select|Wrap|Line Numbers
  1.  private List<string> getData(string sensorID)
  2.         {
  3.             cmdText = "SELECT ID, SensorID, Temperature, Humidity, Light, SoilMoisture, ReceivingDateTime " +
  4.                       " FROM SensorValues SV" + " where SV.ID in (SELECT max(ID) From SensorValues WHERE SensorID LIKE '" + sensorID + "')";
  5.             sqlCon = new SqlConnection(sqlString);
  6.             sqlCom = new SqlCommand(cmdText, sqlCon);
  7.  
  8.             try
  9.             {
  10.                 sqlCon.Open();
  11.                 rd = sqlCom.ExecuteReader();
  12.                 while (rd.Read())
  13.                 {
  14.                     values.Add(rd["SensorID"].ToString());
  15.                     values.Add(rd["Temperature"].ToString());
  16.                     values.Add(rd["Humidity"].ToString());
  17.                     values.Add(rd["Light"].ToString());
  18.                     values.Add(rd["SoilMoisture"].ToString());
  19.                     values.Add(rd["ReceivingDateTime"].ToString());
  20.                 }
  21.                 rd.Close();
  22.  
  23.             }
  24.             catch (Exception args)
  25.             {
  26.                 MessageBox.Show("Error : " + args);
  27.             }
  28.             finally
  29.             {
  30.                 sqlCon.Close();
  31.             }
  32.             return values;
  33.  
  34.         }
  35.  
the problem arises in the following function when called.
Expand|Select|Wrap|Line Numbers
  1.         public void setValues(string sensorID)
  2.         {
  3.             values = this.getData(sensorID);
  4.             textBox1.Text = values[0];
  5.             textBox2.Text = values[1];
  6.             textBox3.Text = values[2];
  7.             textBox4.Text = values[3];
  8.             textBox5.Text = values[4];
  9.             textBox6.Text = values[5];
  10.         }
  11.  
  12.  
  13.  
And the below is the given class which calls the above usercontrol called view.
Expand|Select|Wrap|Line Numbers
  1. List<View> L = new List<View>();
  2.  
  3.         View V;
  4.         public static int total = 7;
  5.         public static String[] SensorIDs = new String[] { "01F4", "0001", "0002", "0003", "0004", "0005", "0006" };
  6.         Terminal T = new Terminal();
  7.  
  8.         public AdminUserControl1()
  9.         {
  10.             InitializeComponent();
  11.             //panel2.Visible = false;
  12.             this.Load += new EventHandler(AdminUserControl1_Load);
  13.         }
  14.  
  15.         void AdminUserControl1_Load(object sender, EventArgs e)
  16.         {
  17. /*View usercontrol is populated in this function*/
  18.  
  19.             double hMaxBy2 = (double)1024 / 2;
  20.             double yMaxBy3 = (double)768/3;
  21.  
  22.             int x=0,y=0;
  23.  
  24.             for (int i = 1; i <= total; i++)
  25.             {
  26.  
  27.  
  28.                 if (i == 3 || i == 5 || i == 9)
  29.                 {
  30.                     x = 0;
  31.                     y++;
  32.                 }
  33.                 if (i == 7)
  34.                 {
  35.                     x = 0;
  36.                     y = 0;
  37.                 }
  38.  
  39.                 V = new View();
  40.  
  41.                 V.Show();
  42.                 V.SetBounds((int)(x * hMaxBy2), (int)(y * yMaxBy3), (int)hMaxBy2, (int)yMaxBy3);
  43.                 splitContainer1.Panel2.Controls.Add(V);
  44.                 L.Add(V);
  45.                 x++;
  46.             }
  47.  
  48.             splitContainer1.Visible = true;
  49.         }
  50.  
  51.  
  52.         private void dataFillerOpenToolStripMenuItem_Click(object sender, EventArgs e)
  53.         {
  54.             System.Timers.Timer Clock = new System.Timers.Timer();
  55.             Clock.Interval = 25000;
  56.  
  57.             Clock.Elapsed += new System.Timers.ElapsedEventHandler(Clock_Elapsed);
  58.  
  59.             Clock.Start();
  60.  
  61.         }
  62.  
  63.         void Clock_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  64.         {
  65.             Filler startFiller = new Filler();
  66.             ThreadStarter cs = new ThreadStarter();
  67.             ThreadStarter.main(null);
  68.  
  69.             for (int i = 0; i < 7; i++)
  70.             {
  71.  
  72.                 L[i].setValues(SensorIDs[i]);
  73.             }
  74.  
  75.  
  76.         }
  77.  
  78.     }    
  79. }
  80.  
  81.  
If any one can help.

Thank you,

Regards,
Syed Ahmed Hussain
Aug 3 '09 #1
11 6901
MrMancunian
569 Recognized Expert Contributor
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
Aug 3 '09 #2
Ahmedhussain
79 New Member
Yes I did set up the break points .... It gave me an error on the following line. :

Expand|Select|Wrap|Line Numbers
  1. textBox1.Text = values[0];
  2.  
Aug 3 '09 #3
Ahmedhussain
79 New Member
I dont know how but when I called the function it got 12 values in it as well..

regards,
Syed Ahmed Hussain
Aug 3 '09 #4
tlhintoq
3,525 Recognized Expert Specialist
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.
Aug 3 '09 #5
Ahmedhussain
79 New Member
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
Aug 3 '09 #6
tlhintoq
3,525 Recognized Expert Specialist
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.
Aug 3 '09 #7
Ahmedhussain
79 New Member
Error: " Exception has been thrown by the target of an invocation." at program.cs
on line :
Expand|Select|Wrap|Line Numbers
  1. Application.Run(new Startup());
Aug 4 '09 #8
Ahmedhussain
79 New Member
I have done this..
Expand|Select|Wrap|Line Numbers
  1.   public delegate void MethodInvoker();
  2.         public void setValues(string sensorID)
  3.         {
  4.             MethodInvoker invoker1 = new MethodInvoker(delegate()
  5.             {
  6.                 values = this.getData(sensorID);
  7.                 textBox1.Text = values[0];
  8.                 textBox2.Text = values[1];
  9.                 textBox3.Text = values[2];
  10.                 textBox4.Text = values[3];
  11.                 textBox5.Text = values[4];
  12.                 textBox6.Text = values[5];
  13.             }
  14.             );
  15.             this.BeginInvoke(invoker1);
  16.         }
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"}"
Aug 4 '09 #9
MrMancunian
569 Recognized Expert Contributor
Sounds like you forgot to subtract 1 from a collection...Co llections start at 0.

Steven
Aug 4 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2287
by: matt | last post by:
Hi all- I'm trying to port an ajax spell-checker (http://www.broken-notebook.com/spell_checker/index.php) to use with the moin moin wiki and have been somewhat successful. (By successful I mean I can spell check using the php backend and my python port running as cgi-bin). My question is this: moinmoin runs on many python web backends (cgi-bin/mod-python/twisted/standalone). My spell-checker backend runs
0
1908
by: Walter Quirtmair | last post by:
Hello, I have a C# WinForms Application that contains various "old" ActiveX-Controls. Due to some unknown reasons recently the "red cross" - problems appears quite often. Without any know reason suddenly some controls (buttons, toolbars...) will be drawn completely white with a red cross inside it. As I know from other postings this happens if there are exceptions during the painting of the controls. The call stack shown in the...
4
7707
by: J Fisk | last post by:
Hi, I've been banging my head on the wall over this for about two days now so any thoughts are much appreciated. I have a static .svg file with embedded onclick="open()"'s all over. The svg is <embed>ded in a minimal .html file. The onclick's work fine in IE w/Adobe SVG viewer 3: click and a new
2
1981
by: Der Script Meister | last post by:
There are a number of possible causes for viewstate errors, but in the past month, I've seen four cases where the Checkpoint "Next Generation" firewall caused this error. Here are the details: This "intelligent" firewall can perform a cross-site scripting attack check when you tell it there's a web server behind it, however, this option appears to remove < and > characters from the form data which breaks viewstate. Known...
4
7792
by: Mau Kae Horng | last post by:
Hello, I have a C# Windows Forms application for machine. Due to some unknown reasons, the application face problems with unexpected exceptions happening, resulting in two red lines forming a red cross across a certain control (the entire form, labels and so on). I get the following message in MessageBox.
11
4289
by: taoberly | last post by:
A few months ago I posted a question about using a file on my hard drive to perform cross-frame scripting and pull data from a server on my company's intranet. I eventually got this working using an HTA file and Internet Explorer. Now I'm tackling a similar issue, but really need to keep the IE menus, navigation buttons, etc. this time around. Assuming a solution exists, I'm guessing it involves using the IE6 SP2 "Mark of the Web"...
0
1467
by: muthalif | last post by:
hi guys, thanks in advance im facing a problem with cross-server insert SET XACT_ABORT ON insert into .REMOTEDATABASE.DBO.REMOTETABLE select * from LOCALDATABASE.DBO.LOCALTABLE PRINT @@ERROR HERE ANY ERROR OCCURES, @@ERROR IS NOT PRINTING, BATCH IS STOPING
0
1022
by: newtechiebug | last post by:
I know that Transform and Pivot are not recognized commands in SQL and I have looked everywhere on how to covert the below query to run properly in SQL, but I can't seem to find the answer. If someone could help, that would be awesome. Thanks! TRANSFORM Count(ConfirmOriginRecords.PHNum) AS SELECT ConfirmOriginRecords.SendZip, Count(ConfirmOriginRecords.PHNum) AS FROM ConfirmOriginRecords GROUP BY ConfirmOriginRecords.SendZip PIVOT...
1
1513
by: Luis Freitas | last post by:
I have a table with the following Fields: Article and 8 fields that are Dates. Under each date is a quantity. I would like to run a query that would have only 3 columns: Article, Date and Quantity Thank you very much
0
4215
by: nfnick | last post by:
HI!... I'm working in Visual Basic 2005 with PostgreSql via the oficial ODBC driver. When i try to insert a new row I get this error message: ERROR: cross-database references are not implemented Here is the code... Dim sel As String sel = "SELECT * FROM ""SCHEMA1"".""CUSTOMERS"" " Dim ds As New DataSet Dim da As New Odbc.OdbcDataAdapter(sel, sConnectionString)
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10264
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6716
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2851
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.