Click here to Skip to main content
15,885,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to call a method from a delegate that can also access some ui controls. Problem occurred during data acquisition, delegate is called whenever memory buffer is filled, then I need to updated some values on display and record the data.

What I have tried:

public delegate void CallbackDelegate();

        static CallbackDelegate myDelegate;
        static int count = 0;
        static private void CallBack_DBEvent()
        {
            count++;
            Display();
            // getting error
            //An object reference is required for the non-static field, method, or property 'WindowsFormsApplication1.Form1.Display()'
        }

        public void Display()
        {
            textBox1.Text = count.ToString();
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myDelegate = new CallbackDelegate(CallBack_DBEvent);
            CallBack_DBEvent();
        }
Posted
Updated 30-Nov-17 20:12pm
v4
Comments
Richard MacCutchan 30-Nov-17 6:40am    
And? What happens when you do so?
Nathan Minier 30-Nov-17 7:29am    
Follow up to Richard's question: Is this running on a different thread?
Rao Tahir 30-Nov-17 8:48am    
I have updated the code, that is the summary of what i am doing in actual program. CallBack_DBEvent() is actually called externally, means "this function is called when memory is full" and then i need to do some operation , like updating number of samples received.

1 solution

Declare your delegate and some "target" methods with matching signatures
delegate void myDelegate(string name);
static void myFunction1(string name)
    {
    Console.WriteLine("1: " + name);
    }
static void myFunction2(string name)
    {
    Console.WriteLine("2: " + name);
    }
Then call them:
myDelegate del = new myDelegate(myFunction1);
del("Joe Smith");
del = new myDelegate(myFunction2);
del("Mike Brown");
You can also call it with an anonymous method:
del = delegate(string name) { Console.WriteLine("Anon: " + name); };
del("Jane Doe");
Or a Lambda:
del = name => { Console.WriteLine("Lambda: " + name); };
del("Mary Jane");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900