1

I have a usercontrol and two classes I want to print result of my class1 into usercontrol.I am sending result from class using this line

((merge.MyControl)(MyControlInstance)).CLIDisplay = e.WorkItem.CustomerId;

my control property to show result is

public string CLIDisplay
        {
            get { return lblResultCLI.Text; }
            set
            {
                    lblResultCLI.Text = value;

            }
        }

but I am getting following Exception when i called a class to my c# form

An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code

Additional information: Cross-thread operation not valid: Control 'tbxEvents' accessed from a thread other than the thread it was created on.
Naushad Qamar
  • 123
  • 3
  • 14
  • 2
    You haven't explained what you're doing in terms of threading, which is obviously important. What research have you done around this error? – Jon Skeet May 11 '12 at 09:15
  • The error is about `tbxEvents` which is kind of missing in the code. – H H May 11 '12 at 09:16
  • possible duplicate of [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) – slugster May 11 '12 at 09:22

1 Answers1

8

You will have to use invoke

this.Invoke((MethodInvoker) delegate
{
   lblResultCLI.Text = value;
});

Next time make sure you use google...

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

This error occurs because lblResultCLI was created on another thread than the one you're running your code on, that is why you will have to use Invoke , so that the code accessing the lblResultCLI control executes on the same thread as it was created on.

Community
  • 1
  • 1
animaonline
  • 3,715
  • 5
  • 30
  • 57
  • 2
    To be honest, this is a poor answer - you have done nothing to explain **why** the OP needs to use Invoke. – slugster May 11 '12 at 09:17
  • 2
    This is a duplicate, why should I bother? I posted a link to a similar question with some good explanations – animaonline May 11 '12 at 09:19
  • thanks its worked ...I have researched before asking question but did't get my problem solved.. – Naushad Qamar May 11 '12 at 09:19
  • @anima - that is good - you provided some context to your answer. *Why should you bother?* If you want people to up vote you, you should give informative answers, rather than just little more than a line of code. – slugster May 11 '12 at 09:22