[Solved] Invalid attempt to read when no data is present

    private void button1_Click(object sender, EventArgs e)
        string name;
        name = textBox5.Text;
        SqlConnection con10 = new SqlConnection("con strn");
        SqlCommand cmd10 = new SqlCommand("select * from sumant where [email protected]");
        cmd10.Connection = con10;
        cmd10.Connection.Open();//line 7
        SqlDataReader dr = cmd10.ExecuteReader();

    if ( textBox2.Text == dr[2].ToString())
        //do something;

When I debug until line 7, it is OK, but after that dr throws an exception:

Invalid attempt to read when no data is present.

I don’t understand why I’m getting that exception, since I do have data in the table with username=sumant.

Please tell me whether the ‘if’ statement is correct or not. And how do I fix the error?

Solution #1:

You have to call DataReader.Read to fetch the result:

SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read()) 
    // read data for first record here

DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:

while (dr.Read()) 
    // read data for each record here
Respondent: Julien Poulin

Solution #2:

You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.

Respondent: Colin Mackay

Solution #3:

I just had this error, I was calling dr.NextResult() instead of dr.Read().

Respondent: Charlie

Solution #4:

I would check to see if the SqlDataReader has rows returned first:

SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
Respondent: dougczar

Solution #5:

I used the code below and it worked for me.

String email="";
    SqlDataReader reader=cmd.ExecuteReader();

String To=email;
Respondent: Aneel Goplani

Solution #6:

I was having 2 values which could contain null values.

    Id = dr["Id"] as int? ?? default(int?);
    Alt =  dr["Alt"].ToString() as string ?? default(string);
    Name = dr["Name"].ToString()

resolved the issue

Respondent: Dev

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published. Required fields are marked *

New ride at Perth's Adventure World a ‘swing on steroids’ - Australasian Leisure Management npp pharma the truth about anabolic steroid drugs and professional sports