Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# login examples

Tags:

c#

winforms

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

like image 499
Joe Avatar asked Aug 17 '10 23:08

Joe


1 Answers

  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().

like image 125
Timwi Avatar answered Nov 08 '22 23:11

Timwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!