Search code examples
c#ado.netdatareader

Move On To Next Record If Condition Not Met


I am trying to move on to the next record in the DataReader if a condition is not met. I am aware that DataReaders are foward-only, so what I am trying to achieve is; while data read, move on to the next record if column x has a null value;

using (OleDbDataReader dr = cmd.ExecuteReader())
{
    try
    { 
        while (dr.Read())
        {
            if (!dr.IsDBNull(0))
            {
                ID = dr.GetString(0).ToString();
            }                     
            if (!dr.IsDBNull(1))
            {
                REFERENCE = dr.GetString(1);
            }
            else
            {
                //this is where I need it to 'abandon' the current record and move on to the next...
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
    finally
    {
        dr.Close();
        dr.Dispose();
        con.Close();
    }
}

I have only put in the part of the code which is relevant so that it's short and straight to the point. Any guidance would be greatly appreciated.


Solution

  • To skip the current record in the DataReader and move on to the next record if a condition is not met, you can use the continue statement. The continue statement allows you to skip the remaining code within the current iteration of the loop and move on to the next iteration. Here's how you can modify your code:

    using (OleDbDataReader dr = cmd.ExecuteReader())
    {
        try
        { 
            while (dr.Read())
            {
                if (!dr.IsDBNull(0))
                {
                    ID = dr.GetString(0);
                }                     
                if (!dr.IsDBNull(1))
                {
                    REFERENCE = dr.GetString(1);
                }
                else
                {
                    // Skip the current record and move on to the next
                    continue;
                }
                
                // Rest of your code for processing the current record
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
        finally
        {
            dr.Close();
            dr.Dispose();
            con.Close();
        }
    }
    

    By using continue, when the IsDBNull condition for column 1 is met, the code will skip the remaining code within the current iteration of the loop and move on to the next iteration, effectively moving to the next record in the DataReader.