Question

I am new to C# and .NET programming. I want to design an application that opens up with a small login screen and when user presses the "Login" button, my program should close the login form and pass to a new form. How can I achieve this simple process?

Thanks.

Was it helpful?

Solution

This could be a solution;

In LoginForm;

public bool IsLoggedIn { get; private set;}
public void LoginButton_Click(object sender, EventArgs e)
{
  IsLoggedIn = DoLogin();
  if(IsLoggedIn)
  {
    this.Close()
  }
  else
  {
    DoSomethingElse();
  }
}

In program.cs

static void Main()
{
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);
  LoginForm loginForm = new LoginForm();
  Application.Run(loginForm);
  if (loginForm.IsLoggedIn)
  {
    Application.Run(new OtherForm());
  }
}

OTHER TIPS

Depending on the overall architecture of your application, I often like to let the main form control launching the login screen.

    //Program.cs:
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }

    //MainForm.cs
    private void MainForm_Load(object sender, EventArgs e)
    {
        this.Hide();
        Login login = new Login();
        if (login.ShowDialog() == DialogResult.OK)
        {
            //make assignments from login
            currentUser = login.User;
        }
        else
        {
            //take needed action
            Application.Exit();
            return;
        }
    }

The challenge here is what form you pass to the Application.Run() method. If you start the application with an instance of the login form and then close that form I believe the application will exit. No doubt there are several ways to handle this...

One way is to pass an instance of your main form to the Application.Run method (this ties the message loop to that form instance and not the login form). In the OnLoad method of the main form you can use a modal dialog to perform the login. i.e.

//--Main form's OnLoad method
protected override void OnLoad(EventArgs ea)
{
    // Remember to call base implementation
    base.OnLoad(ea);

    using( frmLogin frm = new frmLogin() )
    {
        if( frm.ShowDialog() != DialogResult.OK )
        {
            //--login failed - exit the application
            Application.Exit();
        }
    }       
}

If you do use .ShowDialog(), don't forget to wrap it around an using block, or use .Dispose on the login form after you are done. Model dialogs must be manually disposed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top