Pass a label as parameter to a function
c#, delegates, winforms
Solution
Your labels are just fields of your form, as long as you don't actually call methods or set properties on them, you can pass them around as you like:
public void ChangeLabel(string msg, Label label) {
if (label.InvokeRequired)
label.Invoke(new MethodInvoker(delegate {
label.Text = msg;
}));
else
label.Text = msg;
}
Problem
I am creating a utility to insert few records into SQL after performing some calculations. I am using a background worker to stop the app from going into a non-responding state. As the process works I need to change few label values for which I use a delegate. Is it possible to pass my label as parameter to a function which has the delegate so I can re-use some of this code? Below is the function I use to change to change value of label2. For label3 I have used another function that's nearly identical. Is it possible to create a function that accepts label as parameter so that I can pass control name and the required message, and it does the updating for me? Here is my code for changing label2: ``` public void changelabel(string msg) { if (label2.InvokeRequired) label2.Invoke(new MethodInvoker(delegate { label2.Text = msg; })); else label2.Text = msg; } ```