Link to home
Start Free TrialLog in
Avatar of conrad2010
conrad2010

asked on

How can I access a public function in an open usercontrol from another form (WinForms)

I have a usercontrol (uc_Main) of which an instance is loaded and functions as a "main" page. On this control are a dozen or so lables that show total values of invoices, Accounts Receivable and so on.

These labels are updated when the control loads through a public function called "updateStats".

From this control a button opens a modal form (frmFIN_InvoiceClient.cs) that allows me to create invoices. When invoices are being created, I would need to update the totals on uc_Main to reflect the new activities.

I have tried to do it this way:

on frmFIN_InvoiceClient:

private void menuItem6_Click(object sender, EventArgs e)
 {
... create invoices first ...
... then try and run the public function on uc_Main ...
uc_Main uc_Main = new uc_Main();
uc_Main.updateStats();
uc_Main.Update();
}
Which doesn't produce the results I am looking for.

How can I run the updateStats() public function on uc_Main that is currently open?
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
First, I'd say that syntax like:

uc_Main uc_Main = new uc_Main();

is quite horrible and may lead to confusion. I'd neve give a name to an instance same as to the class. Better would be something like_
uc_Main mainControl = new uc_Main();

Anyway, to update the existing control you need to refer to the existing control, not to create a new one.
How to do:

I'd create a special constrictor for the frmFIN_InvoiceClient form, something like :

public frmFIN_InvoiceClient(uc_Main parentControl)
{
    _parentControl = parentControl; // set the field

}

So, now your invoice create form knows about the control to be updated.

The rest should be easy:

private void menuItem6_Click(object sender, EventArgs e)
 {
... create invoices first ...
... then try and run the public function on uc_Main ...

_parentControl.updateStats();
parentControl.Update();
}

Another issue is  - how to pass required info to the uc_Main instance (parentControl). One way is to pass as arguments in the updateStats method. Another way - you call updateStats() and your uc_Main  "interrogates" invoice form to get the information. Probably you have done this already.

Pls ask questions if the idea is not clear
Avatar of conrad2010
conrad2010

ASKER

Hi anarki_jimbel,

I had already accepted previous answer before your posting showed (otherwise I would have split the points).

Thanks for your posting...