How to check if SQLDataReader has no rows

后端 未结 4 718
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 23:51

I am trying to figure out how to check if my SqlDataReader is null or has no rows (meaning the reservation does not exist) and then display a messagebox. For so

相关标签:
4条回答
  • 2020-12-11 00:14
    if(dr.HasRows)
    {
        // ....
    }
    else
    {
        MessageBox.Show("Reservation Number Does Not Exist","Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
    }
    

    SqlDataReader.HasRows Property

    0 讨论(0)
  • 2020-12-11 00:35

    The HasRows property may help you.

    Property Value

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

    0 讨论(0)
  • 2020-12-11 00:36

    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.

    0 讨论(0)
  • 2020-12-11 00:41

    Add this to your code to check:

    sqlCommand cmd = new sqlCommand();
    SqlDataReader dr = cmd.ExecuteReader();
    
    if(dr.HasRows)
    {
        while(dr.Read())
        {
            //code
        }
    }
    
    0 讨论(0)
提交回复
热议问题