我需要打開一個新的表單,如果用戶名和密碼是正確的,但我不能讓這個代碼工作,如果我輸入一個正確的用戶名或密碼它什麼也不做。C#登錄使用SQL Server數據庫不工作
private void login_Click(object sender, EventArgs e)
{
try
{
string connection = @"Data Source=DX-PC;Initial Catalog=login;Integrated Security=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = user.Text;
string passText = pass.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM log WHERE Username = @username and Password = @password", cn);
cmd.Parameters.Add(new SqlParameter("username", userText));
cmd.Parameters.Add(new SqlParameter("password", passText));
SqlDataReader dr = cmd.ExecuteReader();
try
{
dr.Read();
if (dr["Username"].ToString().Trim() == userText && dr["Password"].ToString().Trim() == passText)
{
MessageBox.Show("This message won't Display");
}
}
catch
{
MessageBox.Show("Invalid Username or Password");
}
dr.Close();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
您是否收到任何錯誤? –
可能是一打理由。您'Initial Catalog = login'不存在。你犯錯。你已經爲你的數據庫添加了奇怪的值,爲什麼你會對來自數據庫的字符串使用trim?它更可能使用來自文本框的文本的修剪。 –
不要加入這個俱樂部:http://plaintextoffenders.com/ – Tom