Search code examples
c#winformseventsdisplaydata-recovery

Recover several values contain in an object c#


I start event in my button:

private void button1_Click(object sender, EventArgs e)
{
 _info.Event(value,data); // _info declared above for call from other class
 _info.Event(value2,data2);
}

My Form:

public Form1()
{
 _info = new Info();
 _info.NewData += CustomEvent;
}

And for display:

private void CustomEvent(object sender, MyEvent e)
{
 textBox1.Text = (e.data).ToString();
 textBox2.Text = (e.data).ToString(); //only this value show in both textboxs
}

My question is: I try to use my event for recover several values but i don't know how to separate values in my object for display them in different textboxs?


Solution

  • This is an example on how to work with delegates:
    Of corse you can change the params in the delegate. I chose "string data" & "bool success", but you can change them.


    public class Foo
    {
        public delegate void MyDataDelegate(string data, bool success); //create a delegate (=custom return/param type for event)
        public event MyDataDelegate OnMyEvent; //create event from the type of the early created delegate
    
        private void myMethod()
        {
            //do something 
            bool success = true;
            OnMyEvent?.Invoke("some data", success); //invoke event (use "?" to check if it is null). Pass the params
        }
    }
    

    public class MyClass
    {
        Foo myFoo;
    
        public MyClass()
        {
            myFoo = new Foo();
            myFoo.OnMyEvent += OnMyEventtriggered; //subscribe to the event in the costructor of your class
        }
    
        private void OnMyEventtriggered(string data, bool success)
        {
            //do something
        }
    }