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);
}
I tried my idea and it answered my question. What I did was to show the fetched data in datagridview then I created a condition if the datagridview has a record then my records will not be saved and if the datagridview doesn't have any record, then the record will be saved.
Thanks Everyone!