Label in winform access

Rajkumar Rao 100 Reputation points
2023-10-15T09:53:20.04+00:00

Hi ,

@Karen Payne MVP ,had read a lot of code blocks from you in github but i am a new learner in c# and like to ask something very small . I have a form and a class. In the Form named as Form1, i have a label which i would like to access in separate class. so how do i do it. I have read that for this, i have to create a instance of the form but i want to save my application from creating un-necessary objects as my focus is on memory and performance. So, can you please suggest what alternative left for me. so Please also suggest the best approach in terms of memory and performance . I won't mind sharing an example from you .

Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-10-15T11:48:41.0466667+00:00

    My recommendation is to not access a label on your form from a class, instead use an event that when invoke and listened to from the form makes a decision to alter the label e.g. change the label foreground color based on a logical decision.

    Using an event as per above cost virtually nothing in regards to memory.

    In the following project, I show how to use an event to update the foreground color of a label base on if a int value is odd or even.

    E1

    Form code

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Operations.ColorsChanged += Operations_ColorsChanged;
        }
    
        private void Operations_ColorsChanged(Color color)
        {
            label1.ForeColor = color;
        }
    
        private void UpdateValueButton_Click(object sender, EventArgs e)
        {
            Singleton.Instance.Value += 1;
            Operations.DoSomeWork();
            label2.Text = $@"Singleton value is {Singleton.Instance.Value}";
        }
    }
    

    See the rest of code in the following project.

    In closing, avoid accessing the label from another class by setting Modifiers property from private to public or passing the label to a class and modify a property.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.