This is my first time asking a question on StackOverflow, so I apologize in advance if I ask someone improper. I couldn't find anything to help me while researching this for the past few days, so thank you in advance to anyone who tries to help.
I am making a database that allows people to register and log-in. I am using C# in VS2012. Below is my log-in code and I am running into some trouble when testing. It iterates through everyone in the database and tells me that log-in has failed till it gets to the right user.
private void button1_Click_1(object sender, EventArgs e)
{
try
{
cn.Open();
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
SqlCommand cmd = new SqlCommand("SELECT * FROM [Users]", cn);
cmd.Connection = cn;
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
if (textBox1.Text == (reader["Username"].ToString()) && textBox2.Text == (reader["Password"].ToString()))
{
MessageBox.Show("Logged in");
}
else
{
MessageBox.Show("Login has failed. Please check your Username and Password.");
}
}
cn.Close();
}
As for my registration portion, I'm not sure if it is a VS2012 thing or what, but the information doesn't get saved into the database after I end debug and then go back to debug again.
private void button1_Click_1(object sender, EventArgs e)
{
cn.Open();
SqlCommand cm1 = new SqlCommand("INSERT INTO Users (Username, Password) VALUES (@Username, @Password)", cn);
SqlCommand cm2 = new SqlCommand("INSERT INTO Contact(Name, Address, City, State, PostalCode, Email, PhoneNumber) VALUES(@Name, @Address, @City, @State, @PostalCode, @Email, @PhoneNumber)", cn);
cm1.Parameters.AddWithValue("@Username", textBox1.Text);
cm1.Parameters.AddWithValue("@Password", textBox2.Text);
cm2.Parameters.AddWithValue("@Name", textBox3);
cm2.Parameters.AddWithValue("@Address", textBox4);
cm2.Parameters.AddWithValue("@City", textBox5);
cm2.Parameters.AddWithValue("@State", textBox6);
cm2.Parameters.AddWithValue("@PostalCode", textBox7);
cm2.Parameters.AddWithValue("@Email", textBox8);
cm2.Parameters.AddWithValue("@PhoneNumber", textBox9);
try
{
int affectedRows = cm1.ExecuteNonQuery(); //+cm2.ExecuteNonQuery();
if (affectedRows > 0)
{
MessageBox.Show("Insert Sucsess!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Insert Failed!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
cn.Close();
}