tags:

views:

78

answers:

2

Hi,

I am having trouble hiding my main form for a login form. Once user has logged in to close login form and show main form.

I have been confusing myself that much I have deleted all code and started fresh. I can hide the login form fine.

I was unable to hide the main form called with

Application.Run(new MainForm());

Login form looks like this:

namespace WindowsFormsApplication1
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string username;
            string password;

            username = TB_username.Text;
            password = TB_password.Text;

            if (User.Login(username, password))
            {
                Globals._Login = true;

                // Close login form
                this.Dispose(false);

            }
            else
            {
                MessageBox.Show("Login Failed");
            }

        }
    }
}

I cant figure out how to hide then show the main form once login has passed.

Thanks any examples would be great

A: 

Use the ShowDialog() function on the login form to load the login form from within the main form of the application. This will prevent the MainForm being displayed until after the LoginForm has finished.

private void MainForm_Load(object sender, EventArgs e) {
    var loginForm = new LoginForm();
    loginForm.ShowDialog();
}
ShaneB
+3  A: 
  1. Use ShowDialog() to open the login form. Then you don’t need to hide or disable the Mainform yourself. In fact, if you want the login form to appear at the beginning of the application, consider showing it before even loading the Mainform:

    static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        DialogResult result;
        using (var loginForm = new LoginForm())
            result = loginForm.ShowDialog();
        if (result == DialogResult.OK)
        {
            // login was successful
            Application.Run(new Mainform());
        }
    }
    
  2. Inside your login form, in button1_Click, use

    DialogResult = DialogResult.OK;
    

    to close the login form and pass the OK result to the Mainform. There is no need for Dispose().

Timwi
Thanks worked a treat.
Joe