views:

101

answers:

3

Hi,

I have a simple windows application where I have a window with some buttons and labels together with a couple of other classes.

My problem is that I have some methods in the classes in which I would like to update some labels in the main form. How is it possible to access the labels directly from the classes?

thanks

EDIT: A little piece of code will help

A: 

You could just send in a reference to the Form that contains the labels, or references to the labels themselves, but that links your code to your GUI and so I would not recommend it. Rather, I'd suggest that in the classes you create events, raise them when an update is needed, then you set up the Form to listen for those events and update the GUI as needed.

I'm assuming that the classes are "worker" classes whose methods are called by the Form in some way.

ho1
+1  A: 

The labels on the form are private by default (if added from designer)
One possibility (not recommended) is to change them to public.
A better option would be to add Properties/Methods to set their values.

Itay
noted but i am stuck.I made the following funcion but still cannot access it: public ToolStripStatusLabel StatusLabel (string newStatus) { tlsStatusLabel.Text = newStatus; return tlsStatusLabel; }
mouthpiec
@mouthpiec - sounds like you have an instance of 'System.Windows.Forms.Form' but you need to cast to an instance of 'MyForm' - which is where your labels are declared as Properties.
Andras Zoltan
A: 

Why not fish directly into the Form's controls collection, using perhaps the Control ID as the identifier?

public class LabelChanger
{
  public static void SetLabelText(Form form, string labelID, string labelText)
  {
    Label lbl = form.Controls["labelID"] as Label;
    if(lbl != null)
      lbl.Text = labelText;
  }
}

Then, given a form, you can do this -

Form f = [[get your form]];
LabelChanger.SetLabelText(f, "lblWhatever", "New Label Text");

If those labels are contained within other containers (Panel controls, GroupBox controls etc) then you will have to write a recursive search - however, this would be a good start.

Andras Zoltan