简体   繁体   中英

How to open a new form then from the second form go back to the first form without closing and reopening the first form

I am trying to simulate a login to a application. I want to open from the Login Form, the main form(when the Login is successful). I have a button on the main form that when clicked must freeze the main form open the Login form and after loging from the Login form unfreeze the same main form

I will give you an example:

Simple login and verification.

Important code:

Login_in f2 = new Login_in();//Create login window
this.Hide();//Hide the main window
f2.ShowDialog();//Show login window
this.Show();//Show main window

Main window:

private void Button1_Click(object sender, EventArgs e) {
Login_in f2 = new Login_in();
while (true)
    {
    this.Hide();
    f2.ShowDialog();
    if (f2.DialogResult == DialogResult.OK)
    {
this.Show();
MessageBox.Show("Verification Success!");
break;
    } 
else if (f2.DialogResult == DialogResult.Cancel)
    {
    this.Show();
    MessageBox.Show("Verification Failed");
    break;
    }
f2.Close();
    }
    }

在此处输入图像描述

Login Window:

private void Button1_Click(object sender, EventArgs e) {
//Personal test database
string myconn = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = Test; Integrated Security = True";
SqlConnection conn = new SqlConnection(myconn);
string sql= $"select * from Test.dbo.demoAccount where userid='{ AccountTb.Text}' and password='{PassTb.Text}'";
try
    {
conn.Open();
SqlCommand sqlCommand = new SqlCommand(sql, conn);
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.HasRows)//Satisfy the user name and password are consistent, enter the next interface
    {
this.DialogResult = DialogResult.OK;
    } else
    {
this.DialogResult = DialogResult.Cancel;
    }
conn.Close();
    } catch (Exception o)
    {
MessageBox.Show(o.ToString());
    }
    }

在此处输入图像描述

OutPut:

在此处输入图像描述

If you have questions about my code, please comment below. Update the problem, I will continue to improve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM