I have a Windows form which is taking forever to load data into my datagridview.  I keep getting the error in this line:       dataGridView1.Rows.Add(row);   Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.  Here is my code:      public List&lt;string&gt; _checked = new List&lt;string&gt;();      private void getBarcodProperty()     {                         string query = "select Name from RfidUnic where Barcode = @barcode";          while (true)         {             while (_checked.Count &gt; 0)             {                 SQLiteCommand cmd = new SQLiteCommand(query, sqliteConnection);                 cmd.Parameters.AddWithValue("@barcode", _checked[0]);                 sqliteConnection.Open();                  SQLiteDataReader da = cmd.ExecuteReader();                  if (da.Read())                 {                     if (!da.IsDBNull(0))                     {                         string[] row = new string[] { da[0].ToString(), "1", _checked[0] };                         dataGridView1.Rows.Add(row);                         _checked.RemoveAt(0);                     }                 }                 else                 {                     string[] row = new string[] { "empty", "1", _checked[0] };                     dataGridView1.Rows.Add(row);                     _checked.RemoveAt(0);                 }                  sqliteConnection.Close();             }         }     }   Please show me where I am going wrong  Thanks
749
I have a scenario. (Windows Forms, C#, .NET)   There is a main form which hosts some user control. The user control does some heavy data operation, such that if I directly call the UserControl_Load method the UI become nonresponsive for the duration for load method execution. To overcome this I load data on different thread (trying to change existing code as little as I can)   I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.   Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.    The pseudocode would look like this:  CODE 1  UserContrl1_LoadDataMethod() {     if (textbox1.text == "MyName") // This gives exception     {         //Load data corresponding to "MyName".         //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage.     } }   The Exception it gave was     Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.   To know more about this I did some googling and a suggestion came up like using the following code  CODE 2  UserContrl1_LoadDataMethod() {     if (InvokeRequired) // Line #1     {         this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));         return;     }      if (textbox1.text == "MyName") // Now it wont give an exception     {     //Load data correspondin to "MyName"         //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage     } }   BUT BUT BUT... it seems I'm back to square one. The Application again  become nonresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.  I don't know whether I perceived this right or wrong. I'm new to threading.  How do I resolve this and also what is the effect of execution of Line#1 if block?  The situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.   So only accessing the value so that the corresponding data can be fetched from the database.
98616
I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime?
80278
I'm trying to get images to display in a WPF ListView styled like a WrapPanel as described in this old ATC Avalon Team article: .    When I try to populate the ListView with a LINQ-to-Entities queried collection of ADO.NET Entity Framework objects I get the following exception:  Exception     Items collection must be empty before   using ItemsSource.   My code&hellip;  Visual Basic  Private Sub Window1_Loaded(...) Handles MyBase.Loaded     ListViewImages.ItemsSource = From g In db.Graphic _                                  Order By g.DateAdded Ascending _                                  Select g End Sub   XAML  &lt;ListView Name="ListViewImages"           SelectionMode="Single"           ItemsSource="{Binding}"&gt;     &lt;local:ImageView /&gt; &lt;/ListView&gt;   I put a breakpoint on that line.  ListViewImages.ItemsSource is Nothing just before the LINQ assignment.
12512
Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.  If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.  How can I do something like that?  PS: There is no loop in the run() method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.
52560
I am getting "Error System.QueryException: List has no rows for assignment to SObject".   Line 1: Account ac = [select id from Account where name='testaccount' limit 1] Line 2: if(ac != null) {           //do something         }   I got the above error in line 2 if there is no record.   Any help?
12750
Which is the simplest way to update a Label from another Thread?   I have a Form running on thread1, and from that I'm starting another thread (thread2).  While thread2 is processing some files I would like to update a Label on the Form with the current status of thread2's work.   How could I do that?
36256
we are facing a serious issue. We have a batch APEX job running daily which makes updates on records fulfilling certain conditions. There is another job running parallel to this, in some cases updating or accessing to the same records than the batch job and hence, causing the error:     Update failed. First exception on row 400 with id XXX; first error:    UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record or 200    records:   So, I had then read that in order to fix this kind of error you should use FOR_UPDATE in your select statement (records that have to be updated). The problem is, that you can not use FOR UPDATE for batch jobs. We tested this and effectively, we get the error:     System.QueryException: Locking is implied for each batch execution and   therefore FOR UPDATE should not be specified      It will however lock the records within each execution of execute. See   QueryLocator.getQuery()usage:      You cannot use the FOR UPDATE keywords with a getQueryLocator query to   lock  a set of records. The start method automatically locks the set   of records in  the batch.   Could you find a solution to this?. We would like to handle this in the code itself, because we don't have the permission to schedule the batch job for another time as the another job.
37422
I'm getting this error every few days. I won't see the error for a few days then I'll get a flurry of 20 or so all with in a minute or so.  I've been very thorough going throw my code so that I'm using this basic setup for my DB access.  try {   myConnection.Open();   mySqlDataAdapter.Fill(myDataTable);   myConnection.Close(); } Catch (Exception err) {   if (myConnection.State != ConnectionState.Closed) myConnection.Close();   throw err; }   The way I understand it this should execute my queries and immediately release the connection back to the pool but if something goes wrong with the query then I catch the excpetion close my connection then throw the error up, which eventually gets trapped at the application level and logs and emails me the error.  Even using this throughout my code I'm still running across the issue. What can I do to diagnose the root cause of the issue?
59355
DataGridView, for example, lets you do this:  DataGridView dgv = ...; DataGridViewCell cell = dgv[1,5];   but for the life of me I can't find the documentation on the index/square-bracket operator.  What do they call it?  Where is it implemented?  Can it throw?  How can I do the same thing in my own classes?  ETA: Thanks for all the quick answers.  Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like public object this[int x, int y]{ get{...}; set{...} }; the indexer for DataGridView does not throw, at least according to the documentation.  It doesn't mention what happens if you supply invalid coordinates.  ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates.  Fair warning.
63591
According to : Access to the threads table does not require a mutex  and has minimal impact on server  performance. The other sources have negative performance consequences because they require a mutex.   So yes, I want to use threads table to examine running queries. The trouble is, the PROCESSLIST_INFO column does not contain the full query. It just contains a truncated version of the query. There is a flag viz performance_schema_max_sql_text_length which controls how many bytes are allocated for the SQL query. But it seems to affect the events_statements_history_long table. There is no change in the thread table output. There is also the events_statement_current table. But it is not clear if accessing that table affects performance or not.
121748
I'm running into a performance problem with a query that I can't seem to get my head around.  I pulled the query out of a cursor definition.  This query takes seconds to execute  SELECT A.JOBTYPE FROM PRODROUTEJOB A WHERE ((A.DATAAREAID=N'IW') AND ((A.CALCTIMEHOURS&lt;&gt;0) AND (A.JOBTYPE&lt;&gt;3))) AND EXISTS (SELECT 'X' FROM PRODROUTE B WHERE ((B.DATAAREAID=N'IW') AND (((((B.PRODID=A.PRODID) AND ((B.PROPERTYID=N'PR1526157') OR (B.PRODID=N'PR1526157'))) AND (B.OPRNUM=A.OPRNUM)) AND (B.OPRPRIORITY=A.OPRPRIORITY)) AND (B.OPRID=N'GRIJZEN'))) AND NOT EXISTS (SELECT 'X' FROM ADUSHOPFLOORROUTE C WHERE ((C.DATAAREAID=N'IW') AND ((((((C.WRKCTRID=A.WRKCTRID) AND (C.PRODID=B.PRODID)) AND (C.OPRID=B.OPRID)) AND (C.JOBTYPE=A.JOBTYPE)) AND (C.FROMDATE&gt;{TS '1900-01-01 00:00:00.000'})) AND ((C.TODATE={TS '1900-01-01 00:00:00.000'})))))) GROUP BY A.JOBTYPE ORDER BY A.JOBTYPE   The actual execution plan looks like this.    Noticing the server wide setting was set to MaxDOP 1 I tried playing around with maxdop settings.  Adding OPTION (MAXDOP 0) to the query, or changing the server settings results in much better performance and this query plan.    However, the application in question (Dynamics AX) doesn't execute queries like this, it uses cursors.  The actual code captured is this.  declare @p1 int set @p1=189527589 declare @p3 int set @p3=16 declare @p4 int set @p4=1 declare @p5 int set @p5=2 exec sp_cursoropen @p1 output,N'SELECT A.JOBTYPE FROM PRODROUTEJOB A WHERE ((A.DATAAREAID=N''IW'') AND ((A.CALCTIMEHOURS&lt;&gt;0) AND (A.JOBTYPE&lt;&gt;3))) AND EXISTS (SELECT ''X'' FROM PRODROUTE B WHERE ((B.DATAAREAID=N''IW'') AND (((((B.PRODID=A.PRODID) AND ((B.PROPERTYID=N''PR1526157'') OR (B.PRODID=N''PR1526157''))) AND (B.OPRNUM=A.OPRNUM)) AND (B.OPRPRIORITY=A.OPRPRIORITY)) AND (B.OPRID=N''GRIJZEN''))) AND NOT EXISTS (SELECT ''X'' FROM ADUSHOPFLOORROUTE C WHERE ((C.DATAAREAID=N''IW'') AND ((((((C.WRKCTRID=A.WRKCTRID) AND (C.PRODID=B.PRODID)) AND (C.OPRID=B.OPRID)) AND (C.JOBTYPE=A.JOBTYPE)) AND (C.FROMDATE&gt;{TS ''1900-01-01 00:00:00.000''})) AND ((C.TODATE={TS ''1900-01-01 00:00:00.000''})))))) GROUP BY A.JOBTYPE ORDER BY A.JOBTYPE ',@p3 output,@p4 output,@p5 output select @p1, @p3, @p4, @p5   resulting in this execution plan (and unfortunately the same multiple-second execution times).    I've tried several things such as dropping cached plans, adding options in the query inside the cursor definition, ... But none of them seem to get me a parallel plan.  I've also searched google for quite a bit looking for parallelism limitations of cursors but can't seem to find any limitations.  Am I missing something obvious here?  The actual SQL build is SQL Server 2008 (SP1) - 10.0.2573.0 (X64) which i realise is unsupported, but I cannot upgrade this instance as I see fit. I would need to transfer the database to another server and that would mean pulling a fairly large uncompressed backup over a slow WAN.  Trace flag 4199 doesn't make a difference, and neither does OPTION (RECOMPILE).  The cursor properties are:   API | Fast_Forward | Read Only | Global (0)
78597
I keep getting the System.NullPointerException: Attempt to de-reference a null object on my trigger at line 21. I've attempted to add != null to that line and I get an error too. Please see the code below.  trigger UpdateDMAAccount on Account (before insert, before update) { //get set of Postal Codes from leads to be inserted or updated Set&lt;String&gt; BillingpostalCodes = new Set&lt;String&gt;(); for(Account l : trigger.new){ if(l.BillingPostalCode != null){     BillingpostalCodes.add(l.BillingPostalCode);  } } if(BillingpostalCodes.size() &gt; 0){ //create Map of custom object records with Name (PostalCode) as key Map&lt;String,DMA_Value__c&gt; validBillingPostalCode = new Map&lt;String,DMA_Value__c&gt;(); for(DMA_Value__c obj : [SELECT Id, Name, DMA_Value__c FROM DMA_Value__c WHERE Name IN :BillingpostalCodes]){     validBillingPostalCode.put(obj.Name,obj); } for(Account l : trigger.new){     if((Trigger.isInsert || trigger.oldMap.get(l.Id).BillingPostalCode != l.BillingPostalCode) &amp;&amp; validBillingPostalCode.containsKey(l.BillingPostalCode)){          l.DMA__c = validBillingPostalCode.get(l.BillingPostalCode).DMA_Value__c;     }     else if(trigger.oldMap.get(l.Id).BillingPostalCode != NULL || l.BillingPostalCode &amp;&amp; !validBillingPostalCode.containsKey(l.BillingPostalCode)){         //blank value if new PostalCode does not match a record in the Map         l.DMA__c = Null;     }   }  } }
34074
Why this code isn't working? In my mind the next() method should move the cursor for the next item of the list...  List&lt;string&gt; listX = new List&lt;String&gt; {'A','B','C'}; while(listX.iterator().hasNext())     system.debug(listX.iterator().next());   When I try to run it I receive a error message of exceed a governor limit of CPU time. It's happend because the next() method doesn't move the cursor for the next list item. Every time returns "A".
7189
I generate all my columns in a subclassed DataGridView programmatically. However Visual Studio 2008 keeps reading my constructor class (which populates a DataTable with empty content and binds it to the DataGridView) and generates code for the columns in the InitializeComponent method - in the process setting AutoGenerateColumns to false.  This causes errors in design-time compilation which are only solved by manually going into the design code and deleting all references to these autogenerated columns.  How can I stop it doing this?  I have tried:   Making the control 'Frozen' Setting the DataGridView instantiated object protected (suggested in a previous post which referred to )
92971
I'm working on a C# program, and right now I have one Form and a couple of classes. I would like to be able to access some of the Form controls (such as a TextBox) from my class. When I try to change the text in the TextBox from my class I get the following error:     An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog'      How can I access methods and controls that are in Form1.cs from one of my classes?
76894
I am .  I am going to have to update a program to allow deadlocks. Is it possible that SELECT statement will produce deadlock errors? I know that it is only a read lock so multiple selects won't be a problem, but what if there is an INSERT, UPDATE or DELETE statement (with subqueries possible with joins) and a SELECT statement (possible with joins or subqueries)?   Is it possible that the error will be thrown on the SELECT instead of the INSERT, UPDATE or DELETE.
9770
I'm sure you all know the behaviour I mean - code such as:  Thread thread = new Thread(); int activeCount = thread.activeCount();   provokes a compiler warning.  Why isn't it an error?  EDIT:  To be clear: question has nothing to do with Threads.  I realise Thread examples are often given when discussing this because of the potential to really mess things up with them.  But really the problem is that such usage is always nonsense and you can't (competently) write such a call and mean it.  Any example of this type of method call would be barmy.  Here's another:  String hello = "hello"; String number123AsString = hello.valueOf(123);   Which makes it look as if each String instance comes with a "String valueOf(int i)" method.