这是c#中的登录表单 [英] this is login form in c#

查看:61
本文介绍了这是c#中的登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果部分工作得很好。但是其他部分有错误..(其他部分有什么问题)......



这是我的代码。 ..请帮助我....



if part works very well .But the else part has mistakes in it..(what wrong in else part)...

this is my code...please assist me....

SqlConnection con = new SqlConnection(@"Data source=LENOVO-PC\SQLEXPRESS1;Initial catalog=bank;user id=sa;password=123456");
            con.Open();
            SqlCommand cmd = new SqlCommand("select username ,password from login where username='" + textBox1.Text + "' and password='" + textBox2.Text + "'", con);
            SqlDataReader sdr = cmd.ExecuteReader();

            string user = textBox1.Text;
            string pwd = textBox2.Text;
            if (sdr.HasRows)
            {
                while (sdr.Read())
                {

                    if (this.CompareStrings(sdr["password"].ToString(), pwd) && this.CompareStrings(sdr["username"].ToString(), user))
                    {
                        MessageBox.Show("Login");

                    }

                    else
                    {
                        MessageBox.Show("Error");
                    }

                }
            }
            sdr.Close();
            con.Close();

推荐答案

当我向你指出时,你可能会笑得很傻但是我还是去了:



else部分当然永远不会执行,因为SQL select语句只返回表登录中的一行,如果两者都是用户名和密码匹配。

因为只有当它们匹配时才会有一行你可以像这样重写你的代码(只有外部的if是必需的):



You''ll probably laugh yourself silly when I point it out to you, but here I go anyway:

The "else" part will of course never execute, because the SQL select statement will only return a row from the table login if both the username and the password match.
Since there will only be a row if and when they match you can rewrite your code like this (only the outer if is nescessary):

if (sdr.HasRows) // if it has a row then username and password matched
{
    MessageBox.Show("Login");
}
else             // if there is no row they didn't match
{
    MessageBox.Show("Error");
}





如果您的数据模型是正确的,您甚至不必检查是否还有更多不要一行。

请注意:不要通过连接字符串来构造SQL语句,而是使用SqlParameters。



问候,

- Manfred


错误地把我的其他部分放在了while循环中......这就是问题...... br />




这里的解决方案是::

by mistake i put my else part inside the while loop..that''s the problem....


here the solution is::
if (sdr.HasRows)
           {
               while (sdr.Read())
               {

                   if (this.CompareStrings(sdr["username"].ToString(), user) && this.CompareStrings(sdr["password"].ToString(), pwd))
                   {
                       MessageBox.Show("Login");
                   }


               }
           }
           else
           {
               MessageBox.Show("Error");
           }


这篇关于这是c#中的登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆