How can I update a TextBox from a class using events?

I would like to update the form textboxin winforms with data that is processed from the class file.

Example:

Class.RunProcess();

Inside RunProcess, I would like to trigger an event that will update the text box with the text that I pass in the form of a win.

I know that you can do this with events, so I don’t need to publish public textboxor pass it to many methods that I have, I'm just not quite sure how to start.

Edit : Maybe I just don't understand.

I have a window shape with a text box on it.

I have a button that starts the process.

The process is in the class file outside the form class.

Inside this process method, I would like to be able to update the text field in the main form without passing the TextBox as a parameter to all the methods that I will have (currently I have 6 and there will be more).

I thought I could subscribe to an event that would allow me to display a message in a text box while processes were running in my class.

+3
source share
3 answers

Probably time to consider:

  • Associating a text field with your class
  • Model / View / Presenter (MVP)

For # 1 (data binding), you can use the INotifyPropertyChanged interface in your class and raise an event for the changed properties.

public class BusinessModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int _quantity;
    public int Quantity
    {
        get { return _quantity; }
        set 
        { 
            _quantity = value;
            this.OnPropertyChanged("Quantity");            
        }
    }

    void OnPropertyChanged(string PropertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
    }
 }

.Text textBox . .

:

, , , , , , . - , / - MVP/MVC.

+2

, Class.RunProcess ,

public delegate void MyDelegate();

public class MyClass
{
    public event MyDelegate Myevent;

    public void DoSomething()
    {
        this.Myevent();
    }
}
public static class Class
{
    public static void RunProcess()
    {
        txtData.Text += "Message";
    }
}
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        MyClass myClass = new MyClass();
        myClass.Myevent += Class.RunProcess;
    }
}
+1

, TextBox, .

0

Source: https://habr.com/ru/post/1710368/


All Articles