1

I'm trying to display a message in a label which is coming from a WCF callback. My label is in a windows form application. The problem is the label isn't getting set when the callback is fired. I tried to use a Message Box instead of label and it works. There is nothing much of code to show. Here is the callback function.

    public void GetData(string message)
    {
        label1.Text = message;      // This doesn't work
        MessageBox.Show(message);   // This works fine
    }

Can anyone tell why a label is not getting set inside a callback function.

iJade
  • 23,144
  • 56
  • 154
  • 243
  • Try label1.Refresh(); after setting the text. Refresh causes the control to invalidate, and then update (i.e. immediately repaint itself). – Sain Pradeep May 20 '15 at 05:36
  • Is the label dynamic if so is it added to your Form's control collection ? Try using a breakpoint, step through your method checking your variables. – Mark Hall May 20 '15 at 05:39

1 Answers1

0

The call back event is fired on non-GUI thread and you can access GUI controls in GUI thread who created them. You can use Control.Invoke with MethodInvoker to access control (label) in callback event handler.

public void GetData(string message)
{
    label1.Invoke((MethodInvoker) delegate
    {
         label1.Text = message;     
    });
    MessageBox.Show(message);   
}
Adil
  • 146,340
  • 25
  • 209
  • 204
  • modified as you asked. But not it throws the following error `Invoke or BeginInvoke cannot be called on a control until the window handle has been created.` – iJade May 20 '15 at 06:12
  • Are you calling Web service in constructor if so then call it in form load – Adil May 20 '15 at 06:14
  • Actually, `GetData` is a WCF callback function inside a windows desktop app which is triggered asynchronously by the WCF service. I can't call it in form load. – iJade May 20 '15 at 06:37
  • From where you call that web service? also check this question, http://stackoverflow.com/questions/808867/invoke-or-begininvoke-cannot-be-called-on-a-control-until-the-window-handle-has – Adil May 20 '15 at 06:40