Checking whether DataReader is empty

Kevin James picture Kevin James · Oct 22, 2012 · Viewed 19.2k times · Source

My code does not run when the DataReader is empty. Below is my code.

My work is about Date Scheduling. And my problem is about a holiday constraint. When the user enters the dates (start date and end date), the program will check whether the entered dates have any holidays in between. If the DataReader doesn't have any data, the entered dates should be saved, or if the DataReader has data, then the entered dates are not saved and the program gives an error message.

try
{
    econ = new SqlConnection();
    econ.ConnectionString = emp_con;
    econ.Open();
    ecmd = new SqlCommand("SELECT CD_Date FROM CONS_DATES where CD_Date between '" + Convert.ToDateTime(dtpStart.Text) + "' and '" + Convert.ToDateTime(dtpEnd.Text) + "'", econ);
    ecmd.CommandType = CommandType.Text;
    ecmd.Connection = econ;
    dr = ecmd.ExecuteReader();
    while (dr.Read())
    {
        DateTime cdname = (DateTime)dr["CD_Date"];

        //This code is working
        if (Convert.ToDateTime(cdname) >= Convert.ToDateTime(dtpStart.Text) || Convert.ToDateTime(cdname) <= Convert.ToDateTime(dtpEnd.Text))
        {
            MessageBox.Show("Holiday Constraint. Creating Record Denied.");
        } //if

        //This code is not working. When the program fetch with no record, it should be continue to add the record but it's not working
        else
        if (dr == null || !dr.HasRows)
        {
            //In this area is my code for inserting the entered data.
            MessageBox.Show("Add na|!!!. Creating Record Denied.");
        }//if else
    }//while
}//try
catch (Exception x)
{
    MessageBox.Show(x.GetBaseException().ToString(), "Connection Status", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Answer

manas picture manas · Oct 22, 2012

Your problem is, the while loop runs only if dr has one or more records. But, if the dr is null then the while loop will never run.

Better solution is to have a System.Data.SqlClient.SqlDataReader.

And check,

if (!dr.HasRows)
{
    // Your code to save the records, if no holidays found
}
else
{
    // Your code to show the error message, if there is one or more holidays
}