Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using VS2010, I am busy writing a chat application. In my class "Connection", I have a method which reads the receiving messages. In my "form's" code, I have a method that updates the textbox (which is multi line) with the newest message received. How do I go about using a delegate to point to the "AppendTextBox" when the "ReadMessage" method within the connection class is done reading?

Here is some of my code:

C#
Class Connection
{
        private void ReadMessages()
        {
            NetworkStream stream = tcpClient.GetStream();

            if (stream.CanRead)
            {
                byte[] bytesToRead = new byte[1024];
                StringBuilder completeMessage = new StringBuilder();

                int numberOfBytesToRead = 0;

                numberOfBytesToRead = stream.Read(bytesToRead, 0,     bytesToRead.Length);

                completeMessage.AppendFormat("{0}", Encoding.ASCII.GetString(bytesToRead, 0, numberOfBytesToRead));

                
            }
        }
}

Namespace Whatever
{
   public delegate void _UpdateMyTextBox(string message);

   public partial class Form1
   {
       public void AppendTextBox(string message)
        {
            txtMessages.AppendText(message + "\r\n");
        }

   }
}
Posted
Updated 20-Dec-11 11:15am
v2
Comments
Wendelius 20-Dec-11 17:15pm    
Pre tags added

1 solution

You can pass an instance of a delegate[^], pointing to your method, to the Connection Class (probably through the constructor).
At the time of notifying your main form you can simply call the delegate with a string parameter and the function it is pointing to will be executed. For some examples read here[^] (Action<T> is a delegate like your _UpdateMyTextBox).
Hope it helps :)
 
Share this answer
 

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