Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using Visual Studio 2015 Enterprise edition for asp.net project in which i am getting error "
Invalid attempt to read when no data is present
"

Actually the SqlDataReader is executing the command but i am getting this error can anyone explain me where is the wrong

What I have tried:

con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
if (con.State == ConnectionState.Closed)
    con.Open();
string str = "select RoleName from tblRoles";

cmd = new SqlCommand(str, con);
sdr = cmd.ExecuteReader();

string roleName = sdr["RoleName"].ToString();


I am getting error at the last line saying 'Invalid attempt to read when no data is present'
Posted
Updated 4-Mar-18 20:36pm
Comments
Member 8583441 5-Mar-18 2:17am    
I've tried string roleName = sdr.GetValue(1).ToString(); but no use

1 solution

To use a DataReader, you have to tell it to read each line at a time:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT RoleName FROM tblRoles", con))
        {
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                string roleName = (string) reader["RoleName"];
                Console.WriteLine(roleName);
                }
            }
        }
    }
 
Share this answer
 
Comments
Member 8583441 5-Mar-18 3:23am    
Thank you very much sir
OriginalGriff 5-Mar-18 3:38am    
You're welcome!

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