Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys I try to add text to my text box but didn't work and give this error:
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'log_txtbox' accessed from a thread other than the thread it was created on

What I have tried:

private void Events_ClientDisconnected(object sender, ClientDisconnectedEventArgs e)
{
    log_txtbox.Text += Environment.NewLine + DateTime.Now.ToString() + e.IpPort + " : " + "quit";
}
Posted
Updated 16-Mar-21 22:20pm

1 solution

You can't update the UI from another thread. Depending on whether you're using WinForms or WPF, the solution is different.

WinForms:
C#
log_txtbox.Invoke(() => 
{
    log_txtbox.Text += .....;
});


WPF:
C#
this.Dispatcher.Invoke(()=>
{
    log_txtbox.Text += ....;
});
 
Share this answer
 
Comments
daniel honarpishe 17-Mar-21 4:36am    
now give me this error: CS1660
my code :
log_txtbox.Invoke(() =>
{
log_txtbox.Text += Environment.NewLine+ DateTime.Now.ToString()+ e.IpPort.ToString()+" : "+"join";
});
#realJSOP 17-Mar-21 4:46am    
Try doing this:

log_txtbox.Text = string.Concat(log_txtbox.Text, Environment.NewLine, DateTime.Now.ToString(), e.IpPort.ToString())," : join");
daniel honarpishe 17-Mar-21 5:01am    
," : "," : join"; now give here error
#realJSOP 17-Mar-21 5:11am    
I gotta say, be a programmer. I corrected my reply when I realized I had made that error, but it would have been just as simple for you to do it on your own.
Maciej Los 17-Mar-21 4:47am    
5ed!

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