0

I want to check if the sqldatareader is null or not. So tried the following code:

if (x[k]!= DBNull.Value) 
{
 box.Text = Convert.ToString(x[k++]);
 if ((box.Text) != "")
 current[j - 1] = Convert.ToDouble(box.Text);
 else current[j - 1] = 0;
 box.Enabled = false;
}

However while trying to check the value within the datareader, it throws an error,"invalid attempt to read data when no data is present". How else should i check to see if data is there or not.!! please help. here x is an sqldatareader SqlDataReader x = cmd.ExecuteReader(); and cmd is a select commnand..

OMG Ponies
334k85 gold badges536 silver badges508 bronze badges
asked Apr 6, 2011 at 3:35

2 Answers 2

4

You can use SqlDataReader.HasRows - it is true if at least one row of data is present, alternatively you can read through all results using SqlDataReader.Read();

So for your example:

while(x.Read())
{
 //read stuff
}
answered Apr 6, 2011 at 3:37
0

You can do a null check and Has Row before accessing the DataRows.

like this

if(null != x && x.HasRows)
{
//Your code
}
answered Apr 6, 2011 at 3:38
4
  • but still its showing the same error. !! although the if condition is satisfied, it is not able to execute the line box.Text = Convert.ToString(x[k++]); the fieldcount of x shows 6 but then why is it not able to read x[k] ? even when k = 0. Commented Apr 6, 2011 at 4:08
  • Try Quickwatch the value of the x[k]. Commented Apr 6, 2011 at 4:39
  • is it possible to look into the value stored within the datareader? i mean, i dont think there is a way to peep into the value within x[0] or x[1].. Commented Apr 6, 2011 at 5:04
  • Yes using Quick watch feature you can do this. Commented Apr 6, 2011 at 5:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.