views:

265

answers:

1

I know how to manipulate a textbox on a Form, from a Form, but I do not know how to manipulate a textbox from a CLASS in it's own file to a Form.

Can someone explain to me how I would write a Delegate & a CallBack so I could simply call a method from a Class in a different file, and change stuff on a textbox from a different form?

I don't see how I could explain that any better. Thanks for any help!

+3  A: 

Your class should not change the Form.

However, you can create a delegate or an event in your class, and let your class raise that event when some action has to be taken. Your form can attach an eventhandler to this event, and execute the apropriate action.

For instance:

class MyClass
{
   public event EventHandler DoSomething;

   public void DoWork()
   {
         // do some stuff

         // raise the DoSomething event.
         OnDoSomething(EventArgs.Empty);
   }

   protected virtual void OnDoSomething(EventArgs args )
   {
       // This code will make sure that you have no IllegalThreadContext
       // exceptions, and will avoid race conditions.
       // note that this won't work in wpf.  You could also take a look
       // at the SynchronizationContext class.
       EventHandler handler = DoSomething;
       if( handler != null )
       {
           ISynchronizeInvoke target = handler.Target as ISynchronizeInvoke;

           if( target != null && target.InvokeRequired )
           {
               target.Invoke (handler, new object[]{this, args});
           }
           else
           {
                handler(this, args);
           }
       }
   }
}

And, in your Form, you do this:

MyClass c = new MyClass();
c.DoSomething += new EventHandler(MyClass_DoSomething);
c.DoWork();

private void MyClass_DoSomething(object sender, EventArgs e )
{
    // Manipulate your form
    textBox1.Text = " ... ";
}

When you want to pass some data from your class to your form, then you can make use of the generic EventHandler delegate, and create your own EventArgs class, which contains the information that your form needs.

public class MyEventArgs : EventArgs
{
    public string SomeData
    { get; 
      private set;
    }

    public MyEventArgs( string s ) 
    {
        this.SomeData = s;
    }
}

Then offcourse, you'll have to use the generic eventhandler in your class, and pass the appropriate data into the constructor of your own eventargs class. In the eventhandler, you can then use this data.

Frederik Gheysels
Is that already threadsafe or is that todo mean you havent done it yet? I need it to be thread safe as well, do you mind throwing that back in there ?
OneShot
To make it threadsafe, you'll have to inspect whether you've to invoke the eventhandler or not.I'll modify the code ...
Frederik Gheysels
Thank you so much! I'll see if I can make it work now.
OneShot