Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

c# - How to check if SQLDataReader has no rows

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 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've tried putting this code in a few different locations but none seem to fire off the messagebox if no records are returned

if (dr.GetValue(0) == DBNull.Value || !dr.HasRows)
{
    MessageBox.Show("Reservation Number Does Not Exist","Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
    (read records)
}   

My code...

try
{
   using (SqlConnection con = new SqlConnection(connectionString))
   {
      using (SqlCommand cmd = con.CreateCommand())
      {
         con.Open();
         cmd.CommandText = "usp_StoredProcedureName";
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@regnum", regnumber);

         using (SqlDataReader dr = cmd.ExecuteReader())
         {
             //Loop through all the rows, retrieving the columns you need.
             while (dr.Read())
             {
                 lblConf.Text = dr.GetValue(0).ToString();
                 lblName.Text = dr.GetValue(1).ToString() + "," + dr.GetValue(2);
                 lblCompany.Text = dr.GetValue(3).ToString();
                 lblStatus.Text = dr.GetValue(4).ToString();
             }
         }
      }
   }
}
catch (Exception ex)
{
    MessageBox.Show("Can not open connection! ");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
if(dr.HasRows)
{
    // ....
}
else
{
    MessageBox.Show("Reservation Number Does Not Exist","Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}

SqlDataReader.HasRows Property


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...