Accessing a Windows App Object from another Class using C#.NET
I have a simple windows application where I have a win开发者_JS百科dow 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
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.
This was frustratingly difficult for me, and the posts here helped. What I wound up doing is:
public static ToolStripStatusLabel ts = new ToolStripStatusLabel();
public Form1()
{
InitializeComponent();
ts = toolStripStatusLabel1;
...
then, I do this anywhere:
ts.Text = "Some Text.";
Application.DoEvents();
I found that if I didn't add the DoEvents() statement, the status didn't update frequently enough for me. This will help so much with troubleshooting!
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.
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.
精彩评论