I need to change the textbox value from another class, but I can’t do it. Searching in Google realized that this can be done using events or by changing the textbox access modifier in properties to public, and then creating a form object in the class and changing the textbox value through it, which did not work for me. Help please solve the problem.

Option 1:

public class ClientObject { public delegate void MethodChatLog(string message); public event MethodChatLog writeInChatLog; ... public void Process() { Form1 form1 = new Form1(); try { Stream = client.GetStream(); // Получаем имя пользователя userName = GetMessage(); string message = userName + " вошел в чат."; // Рассылаем сообщение о входе в чат всем подключенным пользователям server.BroadcastMessage(message, Id); writeInChatLog(message); ... 

  public partial class Form1 : Form { ClientObject clientObject = new ClientObject(); static ServerObject server; static Thread listenerThread; public Form1() { InitializeComponent(); try { server = new ServerObject(); listenerThread = new Thread(new ThreadStart(server.Listen)); listenerThread.Start(); // старт потока } catch (Exception exc) { server.Disconnect(); } clientObject.writeInChatLog += MessageChatLog; } public void MessageChatLog(string message) { chatLogTB.Text += message + "\r\n"; } } 

Option 2:

 ... public void Process() { Form1 form1 = new Form1(); try { Stream = client.GetStream(); // Получаем имя пользователя userName = GetMessage(); string message = userName + " вошел в чат."; server.BroadcastMessage(message, Id); form1.chatLogTB.Text += message; // ничего не изменяет ... 

    2 answers 2

    It's pretty simple:

    Pass from one form to another this. That is, the instance of this form.

    And make or public the necessary element or create a public function / parameter that does the desired action. So you will have access from the called form, access to the necessary elements of the calling form.

    If, on the contrary, you need to get access to the element you are calling from the calling form, you don’t even need to pass anything. In the calling form, and so there is an instance called. The approach is the same, in principle, simply without passing this :)

      The most correct option is events, because thanks to this mechanism components become loosely coupled.

      Yes, and from a logical point, it looks more correct: Do you want to change data depending on another window? Subscribe to events.

      All that is needed is to create an event in one of the classes, and to subscribe to it in another class.