【问题标题】:if (count == 1) close this form and open form2, how?if (count == 1) 关闭此表单并打开表单2,如何?
【发布时间】:2013-11-25 21:47:51
【问题描述】:

如果 (count == 1) 让它做与目前相同的事情,但不是隐藏,而是关闭和打开另一个表单 (e.x form2),我该如何做?

我已经试过了。关闭();但它最终在打开新表单的代码运行之前关闭了程序。

    private void button1_Click(object sender, EventArgs e)
    {

        try
        {

            string myConnection = "datasource=localhost;port=3306;username=dolfin;password=quack";
            MySqlConnection myConn = new MySqlConnection(myConnection);

            MySqlCommand SelectCommand = new MySqlCommand("select * from database1.logins where username='" + this.username_txt.Text + "' and password='" + this.password_txt.Text + "' ;", myConn);

            MySqlDataReader myReader;
            myConn.Open();
            myReader = SelectCommand.ExecuteReader();
            int count = 0;
            while (myReader.Read())
            {
                    count = count + 1;

            }
            if (count == 1)
            {
                MessageBox.Show("Username and password is correct.");
                this.Hide();
                Form2 f2= new Form2();
                f2.ShowDialog();
        }
            else if (count > 1)
            {

                MessageBox.Show("Duplicate Username and Password... Access Denied!");
            }
            else
                MessageBox.Show("Username and password is not correct... please try again.");
            myConn.Close();
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);
        }
    }

【问题讨论】:

  • 您的代码易受 SQL 注入攻击。
  • 关闭主窗体会结束它的消息循环,代码会从Application.Run(yourMainForm);跳出你的窗体不用关闭,隐藏就够了,不要觉得浪费记忆,我觉得这里不值一提。
  • 我需要关闭它,如果消息不显示也没关系。
  • 该代码非常容易受到攻击!特地在登录!如果在密码文本框中我写“PASSWORD OR 1 = 1”,则用户名和密码将是正确的。
  • 我猜这种代码在一些学校里是作为新手入门的。

标签: c#


【解决方案1】:

您应该在program.cs 文件中进行这样的更改,因为目前您的第一个表单是您的应用程序主表单;它不能在不结束应用程序的情况下关闭,但这很容易改变。

不要只创建一个表单并将其用作整个应用程序的主表单,而是创建您的登录表单,为其启动一个消息循环,当它结束时(即,当表单关闭时)您可以查看一个属性您已经为它设置了(我使用的或者自定义属性)并且基于该结果,您可以有条件地创建一个新表单并为该表单启动一个全新的消息循环,其中第二个表单现在是新的主形式:

Form1 first = new Form1();
Application.Run(first);
if (first.DialogResult == DialogResult.Yes)
{
    Form2 second = new Form2();
    Application.Run(second);
}

【讨论】:

  • 我可以做一个更简单的事情吗?就像当您单击form2中的x按钮(关闭按钮)时,它会杀死taskmanager中的应用程序Code.exe? (例如)
  • @user3024598 这非常简单;它只是几行代码,它完全符合你的要求,而且一点也不复杂。这也是处理问题的语义上适当的方式。您尝试的替代方案很有可能会更难使用,而不是更容易。
猜你喜欢
  • 1970-01-01
  • 2010-12-20
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 2012-11-06
  • 2012-09-22
  • 1970-01-01
相关资源
最近更新 更多