开发者

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.


What about:

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


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜