hi sir,
i have a textbox and loginbutton in first form and wen i click on a valid id in 1st textbox wch is in the database and click on loginbutton it should show the details of that id in the next form which consists of textboxes and a modify button i am unable to know how to do dis please help

Dani AI

Generated

Quick practical summary and safe patterns (based on the thread): two separate concerns need addressing — passing the authenticated record from the login form into the next form, and how the application lifetime is managed so closing the login doesn’t kill the whole program. If Program.Main calls Application.Run(new LoginForm()) then that form is treated as the main message-loop owner; closing it ends the app. (learn.microsoft.com)

Simple, reliable pattern

  • Show the login as a modal dialog, expose the authenticated data as a public property on the login form, and only call Application.Run(...) for the real main form after ShowDialog returns OK. This keeps the message loop tied to the main UI window and makes passing data straightforward.
[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    using (var login = new LoginForm())
    {
        if (login.ShowDialog() != DialogResult.OK)
            return;                 // user cancelled
        var user = login.AuthenticatedUser;
        Application.Run(new MainForm(user));
    }
}

ShowDialog returns a DialogResult and is the common way to implement login dialogs; Application.Run launches the message loop for your main form. (learn.microsoft.com)

More advanced: ApplicationContext

  • If you need finer control (splash, multiple pre-main windows, or custom lifetime rules), derive ApplicationContext, create/manage forms there and call Application.Run(context). This lets you decide exactly when ExitThread() is called. Example patterns are in the docs. (learn.microsoft.com)

Detecting “X” vs programmatic Close

  • CloseReason is not a reliable way to distinguish user click from calling Close(): Form.Close() sets the reason to UserClosing, so you’ll see UserClosing for both. For a robust test you can either set/clear a dedicated flag when you call Close programmatically, set DialogResult on login buttons and treat default/Cancel as user close, or catch the WM_SYSCOMMAND/SC_CLOSE message in WndProc to detect the title-bar X/Alt+F4. The WndProc technique is shown in community examples. (stackoverflow.com)

Tying this back to the thread: and were correct that instantiating and showing the second form is fine; ’s note about Application.Run owning the main form is the crucial bit to fix the lifetime; and for distinguishing close reasons the WndProc or DialogResult approaches are more reliable than relying on CloseReason alone.

Recommended Answers

All 11 Replies

Create an instance of Second Form's object and request for message Show().

....
Form2 a=new Form2();
a.Show();

Close or Hide your first Form (login)
Show a second Form.
Form idInfo = new Form();
idInfo.Show();

This is actually a bit more tricky then its given credit. The problem is, when you run your first form, that is, in the file, you call Application.Run(new Form1); //or whatever the log in form is called.

It then becomes responsible for the thread, if you close it. Then the application exits. so if you want to Close the login form when you are done with it. your application will exit. To keep this from happening you have multiple viable solutions. you could run the main form (the one that will accept the login information) then hide it, and have it call and create the login form. then simply pass the data into the main from when the login is closed.

or, you could create the login form manually in the Main() method, then call Application.Run() with no args, and when you close any forms or all the forms, the program still runs, and then just create an event handler for you main form for onclosed and call Application.exit();

Now for something a little more advanced, you could created an applicationContext class, that would create all your forms for you, and run them in the pattern of your choosing, then pass that class to your Application.Run(ApplicationContext); method.

These are just some ways to handle it, there are more, but when it comes down to it. Its which ever best suits your application. But either way, its very important to remember, just because visual studio creates our main() method, doesn't mean you won't have to edit it from time to time.

Best of luck with you application,
and as always, Happy Coding.

commented: Closing the main form can be tricky, you explained why,thanks! +6

I have a similar issue. I have modified my call to Application.run in the file, so that it is not responsible for the thread.

frmLogin login = new frmLogin();
login.Show();
Application.Run();

The issue I have now is after I log in the second form displays, but the login form does not close. Its just hidden behind my main application form. What do i need to do for the login form to close completely?

login form code when the login button is clicked

/// <summary>
        /// The button that is clicked when logging into the program
        /// </summary>
        /// <param name="sender">The login button that received the event</param>
        /// <param name="e">mouse event args</param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            string email = txtEmail.Text;
            string password = txtPassword.Text;

            if (email != "" && password != "")
            {
                Employee employee = Employee.GetEmployee(txtEmail.Text, txtPassword.Text, out employee);
                if (employee == null)
                {
                    lblLoginVal.Text = wrongLogInMsg;
                    txtPassword.Text = "";
                }
                else
                {
                    //Open Main CRM Form
                    CRMMain crmMainForm = new CRMMain();
                    crmMainForm.employee = employee;
                    crmMainForm.Show();
                    
                }
            }
            else
            {
                lblLoginVal.Text = emptyLogInMsg;
            }
        }

here is the main method for my second form

public CRMMain()
        {
            InitializeComponent();
            frmLogin login = new frmLogin();
            login.Close();
        }

you need to call the close() method from inside the login form's code...

just add the line to this section

//Open Main CRM Form
                    CRMMain crmMainForm = new CRMMain();
                    crmMainForm.employee = employee;
                    crmMainForm.Show();
                   [B]this.Close();[/B]//this will cause the login form
                   //close  after the main form is opened

otherwise you would need to pass the instance of the login form to the main form in order to reference it to close it. your code actually creates a new form, never shows it, but then closes it.

what is unnecessary, but you could do in that way would be make these changes...

//Open Main CRM Form
                    CRMMain crmMainForm = new CRMMain([B]this[/B]);
                    crmMainForm.employee = employee;
                    crmMainForm.Show();

then in the main form constructor reference that for a close like...

public CRMMain([B]Form lgfrm[/B])
        {
            InitializeComponent();
           [B]lfgrm.Close();[/B] 
        }

best of luck :)

commented: Helped correct my code +4

Great that worked! That brings up another issue now. In my and my file I added the following

private void frmLogin_FormClosed(object sender, FormClosedEventArgs e)
 {
            Application.Exit();
 }

This will exit the application when the form is closed, which I do not want to happen unless they click the close icon in the top right on any form. Is there a way to tell when the close icon is clicked vs when i call the close().
thanks

this is only a problem in the login form, because you will need it to be able to exit the application in the event that a user cannot logon, but the form needs to close when you do log in, but there is a simple solution.

Just create a bool variable, that will tell your close event if its being closed because you logged in successfully...

//create a variable with the full class scope.
private bool exitClose = True;
//edit the form closed handler to check for flag
 private void frmLogin_FormClosed(object sender, FormClosedEventArgs e)
 {
if(exitClose == True)
{
            Application.Exit();
}

 }

then just set the value to false if the login is successful like so

//Open Main CRM Form
                    CRMMain crmMainForm = new CRMMain();
                    crmMainForm.employee = employee;
                    crmMainForm.Show();
                     exitClose = false; //prevent the app from closing
                   this.Close();

Works perfectly now, thanks again.

Works perfectly now, thanks again.

No problem, if you could, mark this thread solved.

No problem, if you could, mark this thread solved.

I would if I could. I did not start the thread. Gangadhar619 started this one.

Well maybe they will. I find it unfortunate when a solution has been found, and a thread isn't marked solved. Its much easier when browsing for answers to look search for only solved threads.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.