Link to home
Start Free TrialLog in
Avatar of parabellum
parabellum

asked on

Access and change control from another class.

Hello.
Say i have a Form1(). and a Textbox1 in it. Now i have a class named "myclass" in another myclass.cs file.  (myclass is public). and myclass has a function named foo()

myclass is performing some asynchronous operations in the background.  I want foo() to update
textbox1.  
I know i need to use delegates, but can you help me how to do that with a  sample ?
Thanks.
 
Avatar of Gururaj Badam
Gururaj Badam
Flag of India image


        private MyClass myclass;
        public Form1()
        {
            InitializeComponent();

            myclass = new MyClass();
            myclass.OperationComplete += new Action<string>(myclass_OperationComplete);
        }

        void myclass_OperationComplete(string obj)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(myclass_OperationComplete), new object[] {obj});
                return;
            }

            textbox1.Text = obj;
        }

    class MyClass
    {
        public event Action<string> OperationComplete;

        public void Foo()
        {

            if (OperationComplete != null)
                OperationComplete("OperationCompleted");
        }
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gururaj Badam
Gururaj Badam
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of parabellum
parabellum

ASKER


Thanks. But how will i raise the event from Foo() ?
For example,  say Foo is accepting a input parameter int input:

Foo(int input).
if(input==5)
Invoke  the textbox ====> How will il invoke it ?

Foo is firing an event which is subscribed by Form1 through myclass_OperationComplete method. It then set the value in the required textbox.
public void Foo(int input)
        {

            if (input == 5 && OperationComplete != null)
                OperationComplete("OperationCompleted");
        }

Open in new window

Oooh  how could i miss that ... Thanks a lot :)