I have a WinForm with a DateTimePicker control on it showing a specific date from my SQL database.
When the user clicks it, I have a custom form open to ask if they are sure they want to change the date.
If they click OK they can proceed to change the date using the DateTimePicker and the changes are posted back to my SQL Server database.
If the user clicks Cancel instead, the method exits so no changes are saved to the database.
However, what is annoying me, is even when the user clicks Cancel, the DateTimePicker drop down calendar stays open, which a user may interpret as the action having failed to Cancel. How can I get the DateTimePicker to close an open drop down calendar?
private void datDOA_ValueChanged(object sender, EventArgs e)
{
frmConfirmBox frmCB = new frmConfirmBox("Are you sure you want to change the Date of Accident?");
frmCB.ShowDialog();
if (frmCB.intButton == 0)
{
return;
}
datDOA.Format = DateTimePickerFormat.Long;
//...Connect to Database...//
string strCaseNo = txtCaseNo.Text;
string strConnect = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnect);
linkToDB.Open();
//...Send User Input to Database...//
DateTime dateNewDate = datDOA.Value;
string commandText = "UPDATE tblCases SET DOA = @DOAVal WHERE CaseNo = @CaseNoVal;";
SqlCommand sqlCom = new SqlCommand(commandText, linkToDB);
sqlCom.Parameters.Add("@DOAVal", SqlDbType.DateTime);
sqlCom.Parameters.Add("@CaseNoVal", SqlDbType.VarChar);
sqlCom.Parameters["@DOAVal"].Value = dateNewDate;
sqlCom.Parameters["@CaseNoVal"].Value = strCaseNo;
sqlCom.ExecuteNonQuery();
linkToDB.Close();
}
I’m not sure what are your requirements, but perhaps you could subscribe to the DateTimePicker ValueChanged event and after they changed the selected date, you can ask them if they’re sure that they want to change the date from X to Y. in case they choose cancel you can always roll back to the previous selected date.
EDIT:
Assume the name of your DateTimePicker is dateTimePicker1:
Here is a sample class named DTP which will do just that
Notice that I have declared a DateTime varible named lastSelectedValue in the top. then after the value is being change I’ll ask the user if he wishes to proceed, if he dose I do the SQL thing, if he dosen’t I will set the Value property of the dateTimePicker1 to the lastSelectedValue.