Update one form from another

  • Thread starter Thread starter JohnSouth
  • Start date Start date
J

JohnSouth

Hi

In a c# Windows Forms application (not asp.net) if I've opened 2 or
more non-modal forms using code like:

FormTypeA aForm = new FormTypeA();
aForm .Show();

FormTypeB bForm = new FormTypeB();
bForm .Show();


How do I update a control (e.g. label) in aForm from code in bForm?
And will the update be seen immediately, or on activation?

John South
www.wherecanwego.com
Pangbourne UK
 
Hi John,
Suggest you use events to communicate between forms.

If formA instantiates FormB then
Declare a custom event (say MySpecialEvent) in FormB with the payload that
you want to deliver.

Declare your FormB variable at FormA Class Level and write a
FormB.MySpecialEvent Eventhandler.

The update will occur when events are handled. Depending on where you are in
your code you may have to issue a DoEvents to get a timely update.
If both FormA and FormB are instantiated in FormC then you can still use the
same technique by FormC responding to FormA and then raising an Interrrupt
which is responded to by FormB
Have a look at
http://www.codeproject.com/csharp/eventarguments.asp
HTH.
Bob
 
I'll second bob - events are the most elegant way here.

I shouldn't be posting this, but there is a 'hacky' way to do it
(particularly if you're not familiar with events in .NET). Remember,
Forms are objects - so just add a get accessor, (or a method if you
need to do a whole lotta stuff) to the FormTypeA class, and construct
your bForm passing aForm as a parameter. You can update it before it is
shown, or whenever you like then.

FormTypeA aForm = new FormTypeA();
aForm .Show();

FormTypeB bForm = new FormTypeB(aForm);
// Constructor: public FormTypeB(FormTypeA form)

string newvalue = "test";

bForm.MyAFormObjectProperty.ChangeLabel(newvalue); // Updates the value
bForm .Show();

However, this is poor programming practice and I strongly suggest
events! Once you understand them, they're unbelieveably cool and make
programming far more flexible :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top