Answer the question
In order to leave comments, you need to log in
How to change form object from another class?
I need to change the textbox value from another class, but I can't do it in any way. After searching Google, I realized that this can be done using events or by changing the textbox access modifier in the properties to public, and then creating a form object in the class and changing the textbox value through it, which did not work out for me. Please help me 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); // здесь сообщение должно передаваться в textbox формы, но увы
...
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";
}
}
...
public void Process()
{
Form1 form1 = new Form1();
try
{
Stream = client.GetStream();
// Получаем имя пользователя
userName = GetMessage();
string message = userName + " вошел в чат.";
server.BroadcastMessage(message, Id);
form1.chatLogTB.Text += message; // ничего не изменяет
...
Answer the question
In order to leave comments, you need to log in
Controls need to be changed only from the thread in which they are created, that is, in the main thread!
You can wrap modifying code in delegates Action
and pass it to Control.Invoke()
forms. Example
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question