Nick
Nick

Reputation: 33

Check if datareader is null or has no rows? ASP.NET

So I took over this project and one page is throwing a lot of errors. I would need to refactor the whole thing but as always time is an issue.

In one case the code check's whether a datareader has any rows and if not go to an error page. However as the code is now the datareader can be null (didn't successfully connect to db) and in those cases I can't use

if (!dr.HasRows)
//

becasuse it obviously gives me 'nullreferenceexception was unhandled by code'. I tried with !dr.Read but same thing.

A part of the code is something like

SqlDataReader dr = null;
try
{
//connect to db etc
dr = DbHelper.GetReader("sp_GetCustomer", param);
}
catch
{
//show an error message
}

// and then:
if (!dr.HasRows)
{

}

Any suggestions?

Thanks in advance.

Upvotes: 2

Views: 26641

Answers (2)

to StackOverflow
to StackOverflow

Reputation: 124686

One possibility is:

SqlDataReader dr = null;
try
{
    //connect to db etc
    dr = DbHelper.GetReader("sp_GetCustomer", param);
    if (!dr.HasRows)
    {

    }
}
catch
{
//show an error message
}

Upvotes: 2

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

What about:

if (dr == null || !dr.HasRows) {
    // Do something
}

Upvotes: 9

Related Questions