Fred
Fred

Reputation: 2468

create custom event for string c#

I have the following:

   using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Security.Permissions;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

        namespace FarmKeeper.Forms
    {
        public partial class FarmLogs : Form
        {
            static string errorLogText = "";
            public string changedText = "";

            public FarmLogs()
            {
                InitializeComponent();

                string txtLoginLogPath = @"../../Data/LoginLog.txt";
                StreamReader readLogins = new StreamReader(txtLoginLogPath);
                txtLoginLog.Text = readLogins.ReadToEnd();
                readLogins.Close();

                loadLogs();

                changedText = errorLogText;

                txtErrorLog.Text = changedText;
            }

            public static void loadLogs()
            {
                string txtErrorLogPath = @"../../Data/MainErrorLog.txt";
                StreamReader readErrors = new StreamReader(txtErrorLogPath);
                errorLogText = readErrors.ReadToEnd();
                readErrors.Close();
            }
        }
    }

Now, what I want to do is to check if the string, changedText, changed. I know a little about custom events but I just cannot figure this out, neither the ones on the internet.

IF changedText changed, then set another textbox to that string.

Upvotes: 1

Views: 1413

Answers (1)

ken2k
ken2k

Reputation: 48975

Replace your field by a property, and check if the value changes in the setter. If it changes, raise an event. There is an interface for property changes notification called INotifyPropertyChanged:

public class Test : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string myProperty;

    public string MyProperty
    {
        get
        {
            return this.myProperty;
        }

        set
        {
            if (value != this.myProperty)
            {
                this.myProperty = value;

                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs("MyProperty"));
                }
            }
        }
    }
}

Just attach an handler to the PropertyChanged event:

var test = new Test();
test.PropertyChanged += (sender, e) =>
    {
        // Put anything you want here, for example change your
        // textbox content
        Console.WriteLine("Property {0} changed", e.PropertyName);
    };

// Changes the property value
test.MyProperty = "test";

Upvotes: 5

Related Questions