Home > Back-end >  C# Dynamically update labels
C# Dynamically update labels

Time:12-15

I have the following code that I use to update a label:

private delegate void DisplayDelegate(string message);

private void DisplayMessage(string message)
{
    if (label2.InvokeRequired)
    {
        Invoke(new DisplayDelegate(DisplayMessage), new object[] { message });
    }
    else
    {
        label2.Text = message;
    }
}

It takes in a string message and in this case updates label2.

In the DisplayMessage function is there a way to add a dynamic label option?

Something along the lines

DisplayMessage("Hello World","label1")

The first option being the message and the second option being the label.

If not would anyone know an alternative solution?

Thanks in advance.

CodePudding user response:

A variation of the suggestion by Ralf:

private Action<string, Label> updateLabelDel = (s, l) => l.Text = s;

private void DisplayMessage(string message, Label label)
{
    
    if (label.InvokeRequired)
    {
        label.Invoke((MethodInvoker)delegate { updateLabelDel(message, label); });
    }
    else
    {
        updateLabelDel(message, label);
    }
}

Usage:

DisplayMessage("Hello World", label2);
  • Related