How to check if SQLDataReader has no rows

为君一笑 提交于 2019-11-28 11:53:16
if(dr.HasRows)
{
    // ....
}
else
{
    MessageBox.Show("Reservation Number Does Not Exist","Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}

SqlDataReader.HasRows Property

Moslem7026

Add this to your code to check:

sqlCommand cmd = new sqlCommand();
SqlDataReader dr = cmd.ExecuteReader();

if(dr.HasRows)
{
    while(dr.Read())
    {
        //code
    }
}

The HasRows property may help you.

Property Value

Type: System.Boolean true if the SqlDataReader contains one or more rows; otherwise false.

For some reason when I debug once it hits the while dr.Read() Code it steps out if it does not have a return result

I think what you're seeing here is that SQLDataReader.Read() returns false if there is not a next, or in this case a first record to read.

As others have responded, use the HasRows property to determine if you have any rows in the result set. Depending on what you need to accomplish, you may want to take advantage of the fact that Read() indeed returns false the first time its called for an empty result set.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!