如何检查是否SqlDataReader的没有任何行 [英] How to check if SQLDataReader has no rows

查看:144
本文介绍了如何检查是否SqlDataReader的没有任何行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何检查,如果我的 SqlDataReader的为空或没有行(即保留不存在),然后显示一个消息框。出于某种原因,当我调试,一旦它击中,如果它没有返回结果它走出了虽然dr.Read())代码。



我试过把这个代码在几个不同的地方,但没有似乎断火的消息框,如果没有记录返回

 如果(dr.GetValue(0)== DBNull.Value ||!dr.H​​asRows)
{
MessageBox.Show(预约号码不存在,错误,MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
}
,否则
{
(读取记录)
}

我的代码...

 
{
使用(SqlConnection的CON =新的SqlConnection(的connectionString))
{使用
(CMD的SqlCommand = con.CreateCommand())
{
con.Open();
cmd.CommandText =usp_StoredProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(@ REGNUM,regnumber);

使用(SqlDataReader的博士= cmd.ExecuteReader())
{
//循环遍历所有的行,检索需要的列。
,而(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();
}
}
}
}
}
赶上(异常前)
{
MessageBox.Show(不能打开连接)!;
}


解决方案

 如果(dr.HasRows)
{
// ...
}
,否则
{
MessageBox.Show(预约号码不存在,错误,MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
}

SqlDataReader.HasRows物业


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! ");
}

解决方案

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

SqlDataReader.HasRows Property

这篇关于如何检查是否SqlDataReader的没有任何行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆