Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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! "); } 
like image 591
Tim Avatar asked Sep 26 '12 20:09

Tim


People also ask

How do I know if my DataReader has rows?

The HasRows property returns information about the current result set. If the DataTableReader contains multiple result sets, you can examine the value of the HasRows property immediately after you call the NextResult method in order to determine whether the new result set contains rows.

How do you check if a DataReader is null or empty?

Try this way: stirng query = "SELECT ColumnA FROM MyTable WHERE ColumnB = 'some condition'"; //... initialize connection and command and reader classes //then do: if(reader. Read()) //if there are any value(s) { if(reader. GetValue(0) !=

Which property of SqlDataReader class is used to check if SqlDataReader has rows?

The HasRows property may help you.

Does SqlDataReader need to be disposed?

You don't need the . Close() statement in either sample: it's handled by the . Dispose() call.


1 Answers

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

SqlDataReader.HasRows Property

like image 53
Tim Schmelter Avatar answered Oct 04 '22 08:10

Tim Schmelter