【发布时间】:2020-10-05 12:57:19
【问题描述】:
在下面的代码中,我尝试在gridview 或数据库中添加行,前提是日期输入正确。即使我输入了错误的日期,它也会在gridview 或数据库中添加行。它显示错误,说错误的日期,但仍然将错误的数据添加到数据库中。
private void btn_AddReservation_Click(object sender, EventArgs e)
{
try
{
int clientId = Convert.ToInt32(txtClientId.Text);
int roomNumber = Convert.ToInt32(cb_RoomNumber.SelectedValue);
DateTime dateIn = dtPDateIn.Value;
DateTime dateOut = dtPDateOut.Value;
if(DateTime.Compare(dateIn.Date,DateTime.Now.Date) < 0)
{
MessageBox.Show("The Date In must be = or > Today Date","Invalid Date In",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
else if(DateTime.Compare(dateOut.Date,dateIn.Date) < 0)
{
MessageBox.Show("The Date Out must be = or > Today Date", "Invalid Date Out", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("Reservation Not Added ", "Add Reservation", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (reservation.addReservation(roomNumber, clientId, dateIn, dateOut))
{
dGvReservations.DataSource = reservation.getAllReservations();
room.setRoomFree(roomNumber, "No");
MessageBox.Show("New Reservation Added ", "Add Reservation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"Add Reservation Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
【问题讨论】:
-
学习调试。显示任何一个消息框后,代码中会发生什么?
-
当您的日期错误时,您只需打印出您的日期错误。您不会做任何其他事情,也不会阻止它被添加。
-
您的代码有几个问题... 1) 在日期比较的其他情况下,您将始终显示一个消息框。这是你想要的吗?? 2)你的 if(...addReservation...) 做了一个插入(我认为。在你的例子中不够清楚),这是我认为的问题
-
我只是在学习。请帮我做什么
-
并且在 addReservation 中我写了这段代码 if (cmd.ExecuteNonQuery() == 1) { con.closeConnection();返回真; } 其他 { con.closeConnection();返回假; }
标签: c# sql-server winforms