Missy Missy - 1 month ago 8
C# Question

Can't Return Variable from Auth Form in C#

I have two projects. One is called Main and the other UserAuth. I don't want to run Main unless the user passes UserAuth. I know there is a lot wrong with my code and that's why I'm asking for help. What I would like to do is to return userAuthenticated from this LoginForm. I can't figure out how to do it. I made a public variable userAuthenticated but I have no way of accessing it. Here is my code:

namespace UserAuth
{
public partial class LoginForm : Form
{
public bool userAuthenticated;

private int attempts = 0;

public bool LoginForm() // Error 'LoginForm': member names cannot be the same as their enclosing type UserAuth
{
InitializeComponent();
return (userAuthenticated);
}

private void btnLogin_Click(object sender, EventArgs e)
{ // authenticate user -- works fine }


Called by:

LoginForm lf = new LoginForm();
lf.Show();


Any help would be appreciated.

Answer

I would remove all that global variable and I would work only with the predefined pattern expected by a modal dialog. In other words I would set the property DialogResult of your btnLogin to DialogResult.Cancel through the Winforms designer and then modify the code in the btnLogin_Click

// this is the form constructor, cannot return anything here
public LoginForm()   
{
    InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{ 
    // this method contains your logic to authenticate the user
    // the method returns true if the user is ok or false if not
    bool result = AuthenticateUser();

    // If the user is authenticated close the login form setting OK
    // as the return value
    if(result)
        this.DialogResult = DialogResult.OK;
    // else the return from the form will be DialogResult.Cancel as 
    // set in the button's DialogResult property
}

Now the code that calls the login form should be simply

using(LoginForm fLogin = new LoginForm())
{
    if(DialogResult.OK == fLogin.ShowDialog())
    {
         MessageBox.Show("Login OK");
    }
    else
    {
         MessageBox.Show("Login failed");
    }
}