Search code examples
c#winformsauthenticationpassword-protectionlogin-control

How can I make a control on a referenced form accessible?


I've got this code to invoke a login form from my main form:

private void frmMain_Activated(object sender, EventArgs e)
{
    frmLogin loginForm = new frmLogin();

    if (loginForm.ShowDialog() == DialogResult.OK)
    {
        HHSConsts.userName = loginForm.textBoxUserName.Text;
    }
    else
    {
        HHSConsts.userName = "dbill";
        HHSConsts.pwd = "ppus"; 
        HHSConsts.currentSiteNum = "42";
    }
    loginForm.Dispose();
}

Probably needless to say, I have a TextBox named textBoxUsername on the login form.

The err msg is, "'HHS.frmLogin.textBoxUsername' is inaccessible due to its protection level"

How can I make textBoxUsername "public" so that I can access it from the main form?

UPDATE

I guess it makes more sense to assign the values in the login form itself, and change the main form's code to:

private void frmMain_Activated(object sender, EventArgs e)
{
    frmLogin loginForm = new frmLogin();
    if (loginForm.ShowDialog() != DialogResult.OK)
    {
        HHSConsts.userName = "duckbilled";
        HHSConsts.pwd = "platypus";
        HHSConsts.currentSiteNum = "1967IceBowl";
    }
    loginForm.Dispose();
}

UPDATE 2

So I can do it either way -- as in Update above, or using John Koerner's way:

// login form:
public string UserName { get { return textBoxUsername.Text; } }
public string Password { get { return textBoxPwd.Text; } }
public string SiteNumber { get { return listBoxSitesWithFetchedData.SelectedItem.ToString(); } }

// main form:
private void frmMain_Activated(object sender, EventArgs e)
{
    frmLogin loginForm = new frmLogin();
    if (loginForm.ShowDialog() != DialogResult.OK)
    {
        HHSConsts.userName = "empacadores";
        HHSConsts.pwd = "vaqueros";
        HHSConsts.currentSiteNum = "2015IceBowlII";
    }
    else
    {
        HHSConsts.userName = loginForm.UserName;
        HHSConsts.pwd = loginForm.Password;
        HHSConsts.currentSiteNum = loginForm.SiteNumber;
    }
    loginForm.Dispose();
}

Don't know which one is the "preferred" method, though.


Solution

  • Don't make the control public. Instead expose a property as part of the login form:

    public string UserName {get {return textBoxUserName.Text;}}