none
Multiple parameters with invoke

    Question

  •  

    I understand how to use invoke.  Now I want to create a single method that will let me set the text value of any textbox in the form.  I would like to pass the control reference, the text to set, and have the method do the work.  Here is what I came up with, but I can't get it to work...HELP!

     

    This is the code I am trying:

     

    private void SetText(string text, object tbox)

    {

    Control c = tbox as Control;

    // InvokeRequired required compares the thread ID of the

    // calling thread to the thread ID of the creating thread.

    // If these threads are different, it returns true.

    if (this.textBox1.InvokeRequired)

    {

    SetTextCallback d = new SetTextCallback(SetText);    <--------this is the error line

    this.Invoke(d, new object[] { text, tbox });

    }

    else

    {

    c.Text = text;

    }

    }

     

     

    but I get this error:

    Error 2 No overload for 'SetText' matches delegate 'ScaleReader.Form1.SetTextCallback' 

    Friday, November 09, 2007 4:05 AM

Answers

  • The key is how your callback is defined.  It should be defined as:

     

    Code Block
    public delegate void SetTextCallback ( string text, object target );

     

     

     

    But, then again, if you are defining your own callback then just use strong types anyway:

    Code Block

     

    public delegate void SetTextCallback ( Control target, string text );

     

    private void SetText ( Control target, string text )
    {

       if (target.InvokeRequired)
       {

          target.Invoke(new SetTextCallback(SetText), new object[] { target, text });
       } else
       {

          target.Text = text;
       };
    }

     

     

    Michael Taylor - 11/9/07

    http://p3net.mvps.org

     

     

    Friday, November 09, 2007 2:15 PM

All replies

  • The key is how your callback is defined.  It should be defined as:

     

    Code Block
    public delegate void SetTextCallback ( string text, object target );

     

     

     

    But, then again, if you are defining your own callback then just use strong types anyway:

    Code Block

     

    public delegate void SetTextCallback ( Control target, string text );

     

    private void SetText ( Control target, string text )
    {

       if (target.InvokeRequired)
       {

          target.Invoke(new SetTextCallback(SetText), new object[] { target, text });
       } else
       {

          target.Text = text;
       };
    }

     

     

    Michael Taylor - 11/9/07

    http://p3net.mvps.org

     

     

    Friday, November 09, 2007 2:15 PM
  • I'm an idiot...Thanks. 

     

    I forgot that the delegete definition needed to be changed...

    I kept looking at the code, and didn't look at the definition of the delegate...

    Friday, November 09, 2007 3:07 PM