Click here to Skip to main content
16,016,814 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
while login time its showing one error"Invalid attempt to call Read when reader is closed" my code attached here

C#
SqlConnection SC = new SqlConnection("Data Source=server;Initial Catalog=CSA;Integrated Security=True");
        SC.Open();
         SqlCommand cmd = new SqlCommand("select * from stockuser",SC);
     
        SqlDataReader SDR = cmd.ExecuteReader();
        string a = Txtusername.Text;
        string b = Txtpassword.Text;
     
      while (SDR.Read())
        {
         
            string d = SDR["Username"].ToString();
            string f = SDR["Password"].ToString();
            string g = SDR["role"].ToString();

            if (a.Equals(d) && b.Equals(f) && g.Equals("Admin"))
            {
                Response.Redirect("Admin.aspx");
            }
            else if (a.Equals(d) && b.Equals(f) && g.Equals("User"))
            {
                Response.Redirect("Stock.aspx");

            }

            else
            {
                Label1.Text = "Inavlid Username or Password";
                Label1.ForeColor = System.Drawing.Color.Red;

            }
            SDR.Close();
            SC.Close();

        }
Posted
Updated 24-Jun-15 22:49pm
v3
Comments
Michael_Davies 25-Jun-15 4:44am    
You do not execute the reader command so it is not open. After defining cmd execute it

SDR = cmd.executereader()
Unni R 25-Jun-15 4:46am    
SqlCommand cmd = new SqlCommand("select * from stockuser", SC);

SqlDataReader SDR = cmd.ExecuteReader();
string a = Txtusername.Text;
string b = Txtpassword.Text;

while (SDR.Read())
{ then also same error message
Michael_Davies 25-Jun-15 4:49am    
There must be a problem in the result, test you got a result, use the debugger to examine the reader.

If SDR.HasRows = True
Michael_Davies 25-Jun-15 5:09am    
Sorry...Your SDR.Close is within the loop, it will execute once, close the reader then try to read again.
Unni R 25-Jun-15 5:18am    
yes its working thanku...

1 solution

Um...look at your code:
C#
while (SDR.Read())
  {
      ...
      SDR.Close();
      SC.Close();
  }
So when the loop gets to the bottom, it'll go back to the while test and try to read a row from the now closed reader. (But you don't show the reader being opened in the first place)

Move the two Close calls outside the loop.

Better use a using block to construct the Connection, Command and Reader objects, and they will automatically be closed and Disposed when they go out of scope.
 
Share this answer
 
Comments
CPallini 25-Jun-15 4:55am    
5. Good catch, I suppose my 'solution' is superfluous :-)
OriginalGriff 25-Jun-15 5:07am    
Dunno - I don't see your solution anywhere! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900