Windows窗体登录

kar*_*ddy 2 c# forms windows

当我使用下面的代码时,如果用户名和密码相同,它工作正常,如果我提供了错误的用户名和密码,它会给我留言或登录:

 private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection con = Helper.getconnection();
                con.Open();
                SqlCommand cmd = new SqlCommand("select SupportName, Password from Logins where SupportName='" + txtSupportName.Text + "' and Password='" + txtPassword.Text + "'", con);
                SqlDataReader dr = cmd.ExecuteReader(); 
                string Name = txtSupportName.Text;
                string Pwd = txtPassword.Text;
                while (dr.Read())
                {
                    if ((dr["SupportName"].ToString() == Name) && (dr["Password"].ToString() == Pwd))
                    {
                       // MessageBox.Show("welcome");
                        Form Support = new Support();
                        Support.ShowDialog();

                }
                else
                {
                    MessageBox.Show("SupportName and password are invalid");
                }
            }

            dr.Close();

            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        if (txtSupportName.Text == string.Empty)
        {
            MessageBox.Show("Please enter a value to Support Name!");
            txtSupportName.Focus();
            return;
        }

        if (txtPassword.Text == string.Empty)
        {
            MessageBox.Show("Please enter a value to Description!");
            txtPassword.Focus();
            return;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dan*_*ley 5

您的代码似乎存在一些问题:

  1. 您应该在运行查询之前验证输入

  2. 您应该参数化您的查询(SO上有大量样本)而不是使用字符串连接

  3. 您似乎假设您将从SQL查询中获得结果.您应该检查dr.HasRows详细信息是否正确,或检查是否dr.Read()返回true以确定是否显示消息框

  4. 您应该使用using块处理数据库对象.例如(不确定为什么格式化不起作用):

    使用(SqlConnection con = Helper.getconnection()){...}

而不是调用DisposeClose明确.即使您确实想要明确调用Dispose,Close也应该在finally块中进行调用.

  • 缺少[Little Bobby Tables]链接(http://imgs.xkcd.com/comics/exploits_of_a_mom.png)! (2认同)