I am working on a school project and am having trouble converting a piece of data from a Access database into a string that I can pass to a second form in C#. I know the connection to the database is working and that I am referencing the right table in it to get the information, so I'm not sure what I'm doing wrong. It doesn't show any errors in the code, but every time I run the application, it crashes because it can't find a value from the database for the string at the string accountnumber = reader["Account_Number"].ToString(); line. Is there something I'm doing wrong?
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from User_Info where Username='" +txt_Username.Text+ "' and Password='" +txt_Password.Text+ "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
string accountnumber = reader["Account_Number"].ToString();
while (reader.Read())
{
count = count+1;
}
if (count == 1)
{
MessageBox.Show("Login Successful!", "Success!");
connection.Close();
connection.Dispose();
this.Hide();
User_Account_Screen UAS = new User_Account_Screen();
UAS.Number = accountnumber;
UAS.ShowDialog();
? character and are position dependent. This is critical, you cannot rely on the name of the parameter. If you have a parameter collection with 3 parameters in that collection then those parameters must appear in the same order in the query.ExecuteScalar with a null check as it will return null if no records are returned. I altered the code to just return accountnumber using ExecuteScalar. I also enclosed the column name in brackets which is good practice when including characters outside the range of a-z and 0-9 in your column name.* for your return. Specify your column names instead. This will guard your code against schema changes like columns being added or column order changes.Here is the updated code.
string accountnumber = null;
using(OleDbConnection connection = new OleDbConnection(/*add your connection string here*/))
using(OleDbCommand command = new OleDbCommand("select [Account_Number] from User_Info where Username = ? AND Password = ?", connection))
{
command.Parameters.Add(new OleDbParameter("@username", OleDbType.VarChar)).Value = txt_Username.Text;
command.Parameters.Add(new OleDbParameter("@password", OleDbType.VarChar)).Value = txt_Password.Text;
connection.Open();
accountnumber = command.ExecuteScalar() as string;
}
if (accountnumber != null)
{
MessageBox.Show("Login Successful!", "Success!");
this.Hide();
User_Account_Screen UAS = new User_Account_Screen();
UAS.Number = accountnumber;
UAS.ShowDialog();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With