How can I access a label from another class?

0

I think the question is simple, I have two classes. I'm sorry if the way to program the theme of the thread is a bit sloppy.

The thing is this class throws a thread that refers to the method abrirTTelnet(); of the class Telnet server , how can I do so that from the telnet class can access label1.text of Form1.cs ?

What I want is to be able to modify from the Telnet class a label of the class Form1

The telnet class opens a socket to a server and this server starts sending me a kind of log with a numeric value type, I want that every time the value changes I can modify the text of the label, I have it controlled , what I can not do is to modify the label from the telnet class.

public partial class Form1 : Form
{

    Boolean activo = false;
    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        ThreadStart delegado = new ThreadStart(proceso1);
        Thread hilo = new Thread(delegado);


        if (activo)
        {
            MessageBox.Show("Hilo abortado");
            hilo.Abort();
            activo = false;
        }
        else
        {
            hilo.Start();
            activo = true;
        }
    }


    private void proceso1()
    {
        TelnetServer.abrirTelnet();
    }
}

An example of what is in my telnet class.

public class TelnetServer{

    public static void abrirTelnet(){

      //Aquí habría whiles, condiciones y cosas.  


      if(Si_esta_condicion_se_cumple){
      //Aquí es donde querría hacer referencia a Form1.label.text = data;
      label1.text = "Un string cualquiera"; 
     }

     }
}
    
asked by Aritzbn 18.10.2017 в 14:27
source

2 answers

1

To do it with events is simple, I show you how:

Telnet Class

public class TelnetServer{

   public delegate void pasoDatosHandler(string num);  //Declaramos el delegado indicando que vamos a mandar un string
   public event pasoDatosHandler OnPasoDatos;  //Declaramos el evento

   public void abrirTelnet(){

      //Aquí habría whiles, condiciones y cosas.  
      if(Si_esta_condicion_se_cumple){
       //Aquí es donde querría hacer referencia a Form1.label.text = data;
       if(OnPasoDatos != null) OnPasoDatos(data);   //Ahora, enviamos el dato al otro formulario donde nos tendremos que suscribir a este evento para poder recibir el dato
      }

    }
}

Form1:

public partial class Form1 : Form
{

Boolean activo = false;
public Form1()
{
    InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)
{
    ThreadStart delegado = new ThreadStart(proceso1);
    Thread hilo = new Thread(delegado);


    if (activo)
    {
        MessageBox.Show("Hilo abortado");
        hilo.Abort();
        activo = false;
    }
    else
    {
        hilo.Start();
        activo = true;
    }
}


private void proceso1()
{
    TelnetServer t = new TelnetServer(); //Creamos un objeto del tipo TelnetServer para poder suscribirnos al evento y recibir los datos de la otra clase
    t.OnPasoDatos+=reciboDatos; //Nos suscribimos al evento, esto quiere decir que cada vez que se ejecute el evento en la otra clase vendrá aquí.
}

public void reciboDatos(string texto){  //Esta es la función de callback
    label1.Text = texto;          //Asignamos a label el texto enviado desde la otra clase
}
}

If you do not understand something I can explain it to you, what I would recommend is that you look a bit at how events work because they are very useful

    
answered by 18.10.2017 / 15:28
source
1

Using events to solve your problem, here is my example

//Esta vendria a ser tu clase TelnetServer
public class TelnetServer{
    //Evento lanzado cuando la operación de abrirTelnet no da error y pasa satisfactoriamente
    public event SuccessOperation OnSuccess;

    //Establezco el constructor
    public Telnet(){
        //Inicializo el evento para cuando lo llame si no se le ha asignado nada no de error
        OnSucess += Telnet_OnSuccess;
    }

    //Función llamada al ejecutarse el evento de que todo esta bien al llamar a la función abrirTelnet
    private void Telnet_OnSuccess(){ }

    //La puse public solamente, removí el static para tener acceso al evento
    public void abrirTelnet(){
       /* 
        * Tu código va aquí
        */
       //Esta condición es para que compruebes que se conectó, que abrió la ventana de telnet, en resumen que tu código de arriba esta ok   
       if(todo_esta_bien){
         //Lanzo el evento
         OnSuccess();
       }
    }
}

//Creo el delegado para ser usado en el evento
public delegate void SuccessOperation;

On your form, that is on Form1.cs

public partial class Form1 : Form
{

    Boolean activo = false;
    private TelnetServer telnet;

    public Form1(){
       InitializeComponent();
       //Creo una instancia de la clase TelnetServer para ser usada posteriormente
       telnet = new Telnet();
       //Aqui pongo el código a ejecutar cuando se lanza el evento OnSuccess
       telnet.OnSuccess += Telnet_OnSuccess;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ThreadStart delegado = new ThreadStart(proceso1);
        Thread hilo = new Thread(delegado);


        if (activo)
        {
            MessageBox.Show("Hilo abortado");
            hilo.Abort();
            activo = false;
        }
        else
        {
            hilo.Start();
            activo = true;
        }
    }

    private void proceso1()
    {
        telnet.abrirTelnet();
    }

}

In summary: I do several things, 1 change to public void your openTelnet function, you had it as static, when adding events I need to instantiate the class, 2 I create a delegate to be used as an event in the TelnetServer class, 3 in the constructor of the telnet class I assign an empty function to the OnSuccess event, 4 I create the function that I will assign, 5 I create the private variable telnetServer to be able to work with the properties of that object from Form1, 6 I create the function that will be executed when the TelnetServer event triggers on Form1.

You just have to copy and paste. But inquire a little more that your problem will be given multiple times.

    
answered by 18.10.2017 в 14:54