Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
{"Cross-thread operation not valid: Control 'cmbLateTxt' accessed from a thread other than the thread it was created on."}

What I have tried:

public enum ClientLate
<pre lang="c#">
{
Select = 1,
Insert_Select = 2
}
public void lateTimeMethod(ClientLate C_late, ComboBox cmbLateTxt)
{
using (SqlConnection con = new SqlConnection(_con))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Select_All_Lateness";
con.Open();

if (C_late == ClientLate.Select)
{
cmd.Parameters.AddWithValue("@status", C_late);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
cmbLateTxt.Items.Add(reader[0]);
}
}
else if (C_late == ClientLate.Insert_Select)
{
if (cmbLateTxt != null)
{
int id = int.Parse(cmbLateTxt.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@status", C_late);
cmd.Parameters.AddWithValue("@reason",id);
SetPromptLateness("Reason Submitted Successfully");
int i = cmd.ExecuteNonQuery();
}
Posted
Updated 13-Dec-17 1:48am

1 solution

You cannot access UI elements (controls, forms) at all, except on the thread on which they were created: the UI thread. If you try, you will get a cross thread exception.
So this code:
cmbLateTxt.Items.Add(reader[0]);
cannot be executed on your "new" thread.

To solve this, either
1) Invoke your control: Control.Invoke Method (Delegate) (System.Windows.Forms)[^]
Or
2) Use the BackgroundWorker class (BackgroundWorker Class (System.ComponentModel)[^] and do the control updates in the ProgressChanged event handler.
 
Share this answer
 
Comments
Member 13573938 13-Dec-17 7:58am    
it works to the first IF statement which it load the the content in the database table into the comboBox,
it was the if Else Statement that was throwing this Exception ( "{"Cross-thread operation not valid: Control 'cmbLateTxt' accessed from a thread other than the thread it was created on."}")
OriginalGriff 13-Dec-17 8:01am    
Then it's this bit:
cmbLateTxt.SelectedItem.ToString()
Same problem: you cannot access UI elements at all, except on the thread on which they were created.
Member 13573938 13-Dec-17 8:09am    
how do i invoke a new delegate for cmbLateTxt.SelectedItem.ToString() ???????
in other not to cross - thread operation
OriginalGriff 13-Dec-17 8:13am    
Read the first link I gave you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900