Access form controls from another form

  • Thread starter Thread starter Paez
  • Start date Start date
P

Paez

Hi there.

How can I modify a form control property from another form. Let's say, I
have a frmMain that has a ToolStripMenuItem with the current user info.
Then, I open another form (frmChangeUser) and after I enter a password in
that form, the current user will change and the frmMain ToolStripMenuItem
will also change.

Right now, I have the folowing code:

frmChangeUser:----------------------
(...)
frmMain.CurrentUser = "Administrator";
frmMain.Administrator();
(...)


frmMain:---------------

public static void Administrador()
{
frmMain x = new frmMain();

x.tssUser.Text = CurrentUser;
}

Any help? Thanks in advance...

Paez
 
It depends on whether frmChangeUser is modal or not. If it is modal,
just have some properties on frmChangeUser, and after ShowDialog()
simply read them and update. The next preferred option (regardless of
modality) is to have some event(s); at the simplest:

public event EventHandler UserChanged;

on frmChangeUser which you hook from frmMain (immediately after
creating the form), and in the handler you again read the properties
you expose. You can do the same with a custom event signature
(eventargs), but it is extra work for little gain. Another (slightly
messier) way is to pass the frmMain instance to frmChangeUser (for
instance in the ctor), but this is not very reusable, and is against
best practice; the OO principle here is that frmChangeUser knows about
users (and changing them), and frmMain knows about the menu; let
frmMain update itself when frmChangeUser does something note-worthy.

Does that make sense?

Marc
 
Back
Top