For a windows form application how do I access the label control from a different class than the code hehind.

I have written a Windows form application using .Net.
I have one web form so the application is pretty simple.  On the web form I have a lable control which I use to display status messages. I can update the label in the code behind file for my web form MainForm.cs

 The code behind for the web form MainForm.cs calls a C# class "Scoper". I would also like to be able to update the label control within that class. How can i do that since the label control can be accessed from the main form code behind file MainForm.cs . I just don't know how to get a handle on the label control from my class Scoper
LVL 2
brgdotnetcontractorAsked:
Who is Participating?
 
Todd GerbertConnect With a Mentor IT ConsultantCommented:
Is this a Windows Forms project, or a Web Forms/Website project?
....either way same basic concept applies... you'd need to pass a reference to your form with the label to Scoper. There are a number of ways to do that, the first one that comes to mind is to have Scoper's constructor take a label control as a parameter.

public class MainForm
{
    private Label mainFormLabel = new Label();
    public void SomeMethodOfMainForm()
    {
        Scoper s = new Scoper(this.mainFormLabel);
        s.SomeScoperMethod("Hello World");
    }
}

public class Scoper
{
    private Label theLabel;
    public Scoper(Label label)
    {
        theLabel = label;
    }
    public void SomeScoperMethod(string Message)
    {
        theLabel.Text = Message;
    }
}

Open in new window

0
 
BIOGENIUSConnect With a Mentor Commented:
it's not a good programatic way to access the label direct from another class.
but the good way is to make a method like:
internal void UpdateLabel(string new_value)
{
label1.Text=new_value;
}
then call this method from the other class.
0
All Courses

From novice to tech pro — start learning today.