Try fixing the first lines of your if:
. . .
if( sdr.Read() )
{
MessageBox.Show("Username is found");
. . .
By the way, to reduce the vulnerabilities, consider Parameterized Queries and do not use string concatenations.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
string constr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jettp\Downloads\MockTest\MockTest\Database1.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, Weight FROM MyWeight where Name ='" + txt_Name.Text + "'"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (txt_Name.Text != null)
{
sdr.Read();
MessageBox.Show("Username is found");
txt_Name.Text = sdr["Name"].ToString();
txt_Weight.Text = sdr["Weight"].ToString();
con.Close();
}
else
{
lbl_WarningMsg.Text = "Name not found";
con.Close();
}
i tried using this command to search for the username which is in not found database, but database message kept saying that the name is found in the database. following by an error (System.InvalidOperationException: 'Invalid attempt to read when no data is present.'
)
Try fixing the first lines of your if:
. . .
if( sdr.Read() )
{
MessageBox.Show("Username is found");
. . .
By the way, to reduce the vulnerabilities, consider Parameterized Queries and do not use string concatenations.
Hi @Yee Keong , Welcome to Microsoft Q&A.
You are getting this error because your judgment is wrong.
When searching for a non-existent name, you can still enter the if
, so it will show that it is found, and then index the non-existing value, resulting in an error(Invalid attempt to read when no data is present).
Use if (sdr.HasRows)
.
You could try the following code to get what you wanted.:
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
sdr.Read();
//
MessageBox.Show("Username is found");
//
con.Close();
}
else
{
//
con.Close();
}
}
Regarding this verification, I have an answer on StackOverflow that you can refer to:
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.