Kev*_*mes 2 c# datareader visual-studio-2010
当代码DataReader为空时,我的代码不会运行.以下是我的代码.
我的工作是关于日期安排.而我的问题是节假日限制.当用户输入日期(开始日期和结束日期)时,程序将检查输入的日期之间是否有任何假期.如果DataReader没有任何数据,则应保存输入的日期,或者如果DataReader有数据,则不保存输入的日期,程序会给出错误消息.
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);
}
Run Code Online (Sandbox Code Playgroud)
问题是,while只有dr拥有一条或多条记录时,循环才会运行.但是,如果dr是,null那么while循环永远不会运行.
更好的解决方案是拥有一个System.Data.SqlClient.SqlDataReader.
并检查,
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17682 次 |
| 最近记录: |