Reputation: 69
I am trying to make a while statement that checks if the name that is given by the user exists in the database. If it doesn't he will need type again until name exists in the database.
I am getting and "Invalid attempt to read when no data is present." exception on the second while loop. What should I do?
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
string FirstName1 = (string)reader["FirstName"].ToString();
if (FirstName1 != param.ToString())
{
Console.WriteLine();
Console.WriteLine("Permision Grantet for: {0}",FirstName1);
}
return;
}
while (!reader.Read())
{
string firstname2 = (string)reader["FirstName"].ToString();
if (firstname2 != param.ToString())
{
Console.WriteLine("Permision Grantet for: {0}", firstname2);
}
}
cn.Close();
Upvotes: 1
Views: 337
Reputation: 363
This is what I would do for the given case. I assumed that param is the input variable and also took a scenario where if the user enters the wrong username then the user will be repeatedly prompted for the username until zero is entered.
while(param != "0")
{
Console.WriteLine("Enter Username: ");
param = Console.ReadLine();
com = new SqlCommand("Select username from table_name", cn);
SqlDataReader reader = com.ExecuteReader();
if( reader.HasRows)
{
while (reader.Read())
{
string FirstName1 = reader["FirstName"].ToString();
if (FirstName1 != param.ToString())
{
Console.WriteLine();
Console.WriteLine("Permission Granted for: {0}",FirstName1);
param = 0;
}
return;
}
}
else
{
Console.WriteLine();
Console.WriteLine("Invalid username! Please try again. To quit, press 0.");
}
}
cn.Close();
Upvotes: 1
Reputation: 12326
The second while statement is failing because there is no data in the SqlDataReader. You are checking that exact condition !reader.Read
. Then inside of of the while loop you are trying to read data from the reader.
It feels like some of the code is missing here, but based on what you have you could simply pull the second if statement into the first while loop and make it an else. Just make sure you exit the loop if the first check passes.
Upvotes: 1