【发布时间】:2013-04-20 06:12:06
【问题描述】:
我的 C# 代码有问题。我在 C# 2010 中创建了一个登录表单。当我验证用户名时,我在 while 循环 中使用了一个 if-condition 但问题是,即使用户名和密码正确,它执行else-statement。请帮我解决这个问题。
这是我的代码:
private void btnlogin_Click(object sender, EventArgs e) {
string connection=
@"Data Source=.\SQLEXPRESS;"
+" AttachDbFilename=|DataDirectory|ResturantDB.mdf;"
+" Integrated Security=True; User Instance=True";
SqlConnection cn=new SqlConnection(connection);
try {
cn.Open();
}
catch(Exception) {
// print the exception's message?
MessageBox.Show("Connection to Database failed; check Connection!");
}
SqlCommand cmd=new SqlCommand("SELECT * FROM [Login]", cn);
cmd.Connection=cn;
SqlDataReader reader=null;
reader=cmd.ExecuteReader();
while(reader.Read()) {
if(
txtuser.Text==(reader["Username"].ToString())
&&
txtpass.Text==(reader["Password"].ToString())
) {
//MessageBox.Show( "logged in!" );
Home newhome=new Home();
newhome.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect credentials!");
}
}
}
【问题讨论】:
-
您的登录表中是否只有一行?
-
首先:您似乎以纯文本形式存储密码。别! SO上有很多关于密码散列和加盐的问题。请仔细阅读。第二:您不想查询登录表中的 all 行。只是对应于给定
Username的那个。然后只检查一次。不要在这里使用循环。
标签: c# if-statement while-loop