I am a beginner and would like to implement basic login page using C#.net - web application. I have created database successfully and can test connection worked as well. I get the below error message when the control hits ExecuteReader() command.
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid object name 'UserDB'.
string LoginDbCS =ConfigurationManager.ConnectionStrings["UserDB"].ConnectionString;
string ID = TextBoxUserId.Text;
SqlConnection Conn = new SqlConnection(LoginDbCS);
{
string sCmdStr = "select Password from UserDB where UserID=@ID";
SqlCommand sCmd = new SqlCommand(sCmdStr, Conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "@ID";
param.Value = TextBoxUserId.Text;
sCmd.Parameters.Add(param);
Conn.Open();
SqlDataReader sReader = sCmd.ExecuteReader();
sReader.Read();
if ((string)sReader["Password"]==TextBoxPassword.Text)
{
Label5.Text = "Login Successful";
}
else
{
Label5.Text = "No Records found";
}
sReader.Close();
Conn.Close();
}
}
Looking forward for suggestions to fix this crash.
Well, Your question was answered in the comments by sohaiby , but there are some deeper issues with your code, and you should fix those.
I believe that it's easier to learn good coding standards as a beginner then as someone that has experience with bad coding standards, since people often go to what is familiar when thing go bad.
So, here are some bad practices that you should replace ASAP:
string sCmdStr = "select * from UserDB where UserID=@ID AND Password = @Password";
ExecuteScalar
to get a single value from the database. ExecuteScalar
will return null. read how to handle this here. . SqlConnection
in your case) without a Using
statement. I hope this will help you learn better coding standards and improve your coding skills.
Happy programming!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.