我试图弄清楚如何检查 mySqlDataReader
是否为空或没有行(意味着预订不存在),然后显示一个消息框。出于某种原因,当我在遇到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! ");
}