I'm making a user login screen in c# winforms, I want to be able to check a user's username and password against records in an SQL database as per this link, however my code throws an exception saying "Incorrect syntax near User".
Could anyone help me figure out what's wrong with my code please? offending code is below.
private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
private void LoginBtn_Click(object sender, EventArgs e)
{
//var username = textBox1.Text;
//var password = maskedTextBox1.Text;
try
{
SqlConnection Conn = new SqlConnection("Data Source=***********;Initial Catalog=*********;Persist Security Info=True;User ID=*********;Password=*******");
SqlCommand com = new SqlCommand();
com.Connection = Conn;
Conn.Open();
com.CommandText = ("SELECT (Username) AS User, (Password) as Pass FROM dbname WHERE User='" + textBox1.Text + "'");
SqlDataReader reader = com.ExecuteReader();
var username = textBox1.Text;
var password = maskedTextBox1.Text;
while (reader.Read())
{
if (this.CompareStrings(reader["User"].ToString(), username) &&
this.CompareStrings(reader["Pass"].ToString(), password))
{
MessageBox.Show("Login Authenticated!");
}
else
{
MessageBox.Show("Login failed!");
}
Conn.Close();
reader.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}