Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Updating GUI from object 1

Status
Not open for further replies.

wawalter

Programmer
Aug 2, 2001
125
US
Hello,

I have what I think should be a simple problem, but it is stumping me. I have a form that creates a class to do some work. I want the class to be able to update a status bar on the form.

So far the way I have it working is by passing a reference of the form to the constructor of the object created by the form and then updating the form by having the object call a delegate on the form to run the private update gui method on the form.

I'm sure this isn't the best way to be doing this, but I haven't found a way that makes sense to me. I read some of the multi-thread solutions here, but that seems like overkill for my problem.

Thanks,
Bill
 
You should create a custom event in the class so that the form may register a handler for it. Then, the form can do the status update whenever the child class fires that event. This is ideal since it keeps form-based actions (updating the status bar) within the code of the form itself.

In the child class, you will need to define a delegate variable that defines the structure of the event handlers, along with a "listeners" variable that will hold the registered event handlers:

Code:
public delegate void StatusChanged(String newstatus);
public event StatusChanged SCListeners;

I've made these variables public so that the parent form may modify them. In order for the parent form to register an event handler, it does the following:

Code:
public void UpdateStatus(String statustext) {
    // update the status here, for example:
    txtStatus.Text = statustext;
}

myClass myClassInstance = new myClass();   // creates an instance of the child class
myClass.SCListeners += UpdateStatus;       // adds the local function as a handler for the event

Finally, in order to fire actual events from the child class, you'll need to check to make sure that there are listeners who care about the event, then call them:

Code:
if (SCListeners != null) {
    SCListeners("New status text");
}

I've written this code based on some old work of my own, so there might be a few errors, but hopefully this will get you started. Good luck!
 
Just what I needed.

The only thing I changed was:

myClass.SCListeners += UpdateStatus;

should be

myClassInstance.SCListeners += UpdateStatus;

Thanks a lot.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top