Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a form(form1.cs) and i have a class(Operation.cs) both inside the same project. Its east to update a textBox from within form.cs using textBox1.AppendText("messages"). But how do i update or pass messages to the textBox from Operation.cs . This class is a method group and contains few methods.
Can i use :
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { "messages" });
to achieve the same and defining the following in the form1.cs
C#
private delegate void UpdateStatusCallback(string strMessage);
private delegate void UpdateLogCallback(string strMessage);
        private void UpdateLog(string strMessage)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke(new UpdateLogCallback(UpdateLog), strMessage);
                return;
            }

            txtLog.AppendText(strMessage);
        }

Please help me with the solution!!
Thanks :)
Posted
Updated 6-Jun-14 3:01am
v2

1 solution

No, don't.

The problem is that if your Operation class updates the textbox directly, it can't work without your specific form - and that's bad because you can't reuse it, and you can't change the form without considering the effect on the Operation class.

There are two ways to do this:
1) Have a public method (static or not as needed) in Operation that the outside world can call: it does the operation, and returns the result. The outside world is then responsible to using that result to update it's textbox (or whatever else it wants to use)
2) Have an Event in the Operation class which says "result ready" and have the outside world handle it. The outside world then accesses the result via a public Property, and updates itself.

The first way is good for simple operations that don't take long; the second for long running operations that can't return immediately.

To create an event is easy, this explains it: Transferring information between two forms, Part 2: Child to Parent[^]
 
Share this answer
 
Comments
[no name] 6-Jun-14 9:45am    
5ed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900