Question

I am using the following code to update a label in my class which extends UserControl:

private delegate void LabelChanger(bool signedIn);

public bool SignedIn
{
    get { return _signedIn; }
    set
    {
        _signedIn = value;
        labelChanger(value);
    }
}

private void labelChanger(bool signedIn)
{
    if (label1.InvokeRequired)
    {
        BeginInvoke(new LabelChanger(labelChanger), signedIn);
    }
    label1.Text = signedIn ? "Sign Out" : "Sign In";
}

The problem is that when the code gets to setting the label text, the UI is updated, however I get an `InvalidOperationException on a panel which is the label's parent. Any ideas why? Thanks.

Was it helpful?

Solution

The label1.Text = signedIn ? "Sign Out" : "Sign In"; is executed even when you're in the wrong thread. You should enclose it with an else {}.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top