using (SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
DateTime dt2 = Convert.ToDateTime(rdr["Date"]);
int Classroom = Convert.ToInt32(rdr["ClassroomNo"]);
TimeSpan ST = (TimeSpan)rdr["StartingTime"];
TimeSpan ET = (TimeSpan)rdr["EndingTime"];
TimeSpan span = ET.Subtract(ST);
double Minutesdifference = span.TotalMinutes;
TimeSpan NewTime = (TimeSpan)rdr["StartingTIme"];
for (int i = 1; i <= Minutesdifference; i++)
{
NewTime = NewTime.Add(TimeSpan.FromMinutes(1));
// Response.Write(NewTime + "<br>");
Response.Write(Classroom + "<br>");
Response.Write(ClassroomNo + "<br>");
Response.Write(dt + "<br>");
Response.Write(dt2 + "<br>");
Response.Write(StartTime + "<br>");
Response.Write(NewTime + "<br>");
Response.Write(ST + "<br>");
if ((Classroom == ClassroomNo && dt == dt2 && StartTime == NewTime) || (Classroom == ClassroomNo && dt == dt2 && StartTime == ST))
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
}
}
if (flag == 0)
{
SqlCommand cmd2 = new SqlCommand("spStoreTimeSlotDetails2", con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("@Username", hfUsername.Value);
cmd2.Parameters.AddWithValue("@EmpName", lblFacultyName.Text);
cmd2.Parameters.AddWithValue("@Date", dt);
cmd2.Parameters.AddWithValue("@Day", day);
cmd2.Parameters.AddWithValue("@ST", StartTime);
cmd2.Parameters.AddWithValue("@ET", EndTime);
cmd2.Parameters.AddWithValue("@TimeSlot", hfTmeSlot.Value);
cmd2.Parameters.AddWithValue("@Topic", txtTopic.Text);
cmd2.Parameters.AddWithValue("@ClassroomNo", ClassroomNo);
cmd2.ExecuteNonQuery();
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Data Saved Successfully";
}
else if (flag == 1)
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Time Slot already allocated by some other Employee. Please choose another";
}
我将If Condition转换为for循环。如果该条件为真,则中断for循环,但while(rdr.Read())
方法仍在执行。我只想关闭Reader方法并直接从using(sqlDataReader rdr=cmd.ExecuteReader)
方法出来并执行if(flag == 0)。
答案 0 :(得分:1)
我的假设是在从for循环中断后你仍然想要执行if loop of flag
中的代码,所以只需添加此代码即可在循环中突破rdr.Read()
else if (flag == 1)
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Time Slot already allocated by some other Employee. Please choose another";
break;
}
此代码将确保处理和关闭Reader对象:
using (SqlDataReader rdr = cmd.ExecuteReader())
除了建议的改变之外没什么需要
答案 1 :(得分:0)
while (reader.Read() && !flag)
{
....
for (int i = 1; i <= Minutesdifference; i++)
{
if ((Classroom == ClassroomNo && dt == dt2 && StartTime == NewTime) || (Classroom == ClassroomNo && dt == dt2 && StartTime == ST))
{
flag = 1;
break;
}
else
{flag=0;}
...
}
}
答案 2 :(得分:0)
正如Sergei Yevlakov所建议的,在while循环之前将flag变量设置为0,如下所示。
using (SqlDataReader rdr = cmd.ExecuteReader())
{
flag=0;
while (reader.Read() && !flag)
{
.....
for (int i = 1; i <= Minutesdifference; i++)
{
if ((Classroom == ClassroomNo && dt == dt2 &&
StartTime== NewTime) || (Classroom == ClassroomNo &&
dt == dt2 && StartTime == ST))
{
flag = 1;
break;
}
//no need of else part here now.
...
}
}
}