hashem baddad
hashem baddad

Reputation: 49

Data Grid View : System.InvalidOperationException: 'Cross-thread operation not valid: Control ''

I have tried to find a solution to this problem but I did not find or did not know, I'm new at C#

I found a lot of solutions that talk about (invoke) but I did not know how to fix them on my code ,Everything if find is just a solution for label or textbox, If possible solve the problem

"System.InvalidOperationException: 'Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.'"

Error Message Image

            for (int i = 0; i <= len - 1; i++)
        {

            if (i % 3 == 0)
            {
                split = proxy[proxy_counter].Split(':');
                num.Rows.Add(numlist[i], 0, 0, split[0], split[1], split[2], split[3]);

                proxy_counter++;
            }
            else
            {
                num.Rows.Add(numlist[i], 0, 0, split[0], split[1], split[2], split[3]);
            }

        }

Upvotes: -1

Views: 406

Answers (1)

Guido Zanon
Guido Zanon

Reputation: 3059

The problem is on the MessageBox.Show. You can't change UI from a background thread. in order to do that you need to Invoke (as you said) the MessageBox.Show from the Principal Thread.

Change your MessageBox line for (assuming that that piece of code is inside a Windows Form):

InvokeIfRequired(() =>
    {
        MessageBox.Show("You Enter Less Than 6 Numbers!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    });

private void InvokeIfRequired(Action method)
{
    if (this.InvokeRequired)
    {
        Invoke(method);
    }
}

Upvotes: 0

Related Questions