我正在创建一个Windows窗体应用程序,允许用户从MonthCalendar
中选择值,然后将它们插入到数据库中。
我正在使用以下方法在文本框中显示日期。
private void checkIn_DateChanged(object sender, DateRangeEventArgs e)
{
var monthCalendar = sender as MonthCalendar;
txtcheckIn.Text = monthCalendar.SelectionStart.ToShortDateString();
}
日期在文本框中正确显示,但我正在使用它们,当它们插入数据库时,它们将显示为默认值。 我正在使用以下内容插入值
private void Insert()
{
using (var command = new SqlCommand("INSERT INTO Reservation (NumAdults,NumChildren,RoomType,CheckIn,Checkout) " +
"VALUES (@numAdults,@numChildren,@roomType,@checkIn,@checkout)"))
{
try
{
command.Connection = connection;
connection.Close();
// Enters Reservation fields into the parameters of the SQL Query
command.Parameters.AddWithValue("@numAdults", txtNumAdults.Text);
command.Parameters.AddWithValue("@numChildren", txtNumChild.Text);
command.Parameters.AddWithValue("@roomType", roomTypeBox.GetItemText(roomTypeBox.SelectedItem));
command.Parameters.AddWithValue("@checkIn", txtcheckIn.Text);
command.Parameters.AddWithValue("@checkout", txtcheckOut.Text);
// Opens connection and checks if query affects Reservation table
connection.Open();
if (command.ExecuteNonQuery() > 0)
{
// If the query was successful, alert user and display updated Client Table
MessageBox.Show("Reservation Record Successfully Inserted.");
connection.Close();
displayReservations();
resetReservationFields();
}
else
{
// Insertion failed, show user message
MessageBox.Show("Record Insertion Failed.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error Inserting: No fields entered. \n" + ex);
}
finally
{
connection.Close();
}
数据库中日期的格式是“datetime”,我不明白文本框中的日期会发生什么。