【发布时间】:2012-09-18 13:33:19
【问题描述】:
我试图弄清楚如何检查我的SqlDataReader 是否为空或没有行(意味着预订不存在),然后显示一个消息框。出于某种原因,当我在遇到While dr.Read()) 代码时进行调试时,如果它没有返回结果,它就会退出。
我尝试将此代码放在几个不同的位置,但如果没有返回记录,似乎没有一个会触发消息框
if (dr.GetValue(0) == DBNull.Value || !dr.HasRows)
{
MessageBox.Show("Reservation Number Does Not Exist","Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
(read records)
}
我的代码...
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 语句以检查 if (dr.HasRows){}
-
不,我的 SqlDataReader 将“HasRows”设置为 true...但实际上没有加载任何行。
标签: c# sqldatareader