Setting DateTimePicker to Null

I cannot set the Datetimepicker parameter to Null how to do this. In my project, my requirement is to check DTPf that it is null, for which I need to set the value to Null. The code I'm using is:

{ dateInsert.Format = DateTimePickerFormat.Custom; dateInsert.Text = string.Empty; } 
+7
c # datetimepicker
source share
4 answers

Use the following code:

 dateTimePicker1.Format = DateTimePickerFormat.Custom; dateTimePicker1.CustomFormat = " "; 
+6
source share

Take a variable and set its value when the DateTimePicker value changes

eg.

 DateTime? myselectedDate = null; private void DateTimePicker1_ValueChanged(Object sender, EventArgs e) { myselectedDate = DateTimePicker1.Value; } 
+4
source share

I had a similar question, but I could not find the answer that I liked. However, I came up with a suitable solution. Set the ShowCheckBox property to datetimepicker true. This will check the box next to the date in the field. Then add the following code.

 if (dateTimePicker1.Checked == false) myVariable = ""; else myVariable = dateTimePicker1; 
+3
source share

As noted above, “karthik reddy” you need to use “CustomFormat”, however, to write a null value to the SQL database (for example), your code should check the DateTimePicker when it adds or updates the record, so you need at least two code snippets. Where a) 'dtp_X' is a DateTimePicker control, b) "_NewRecord" is a custom object that is sent back to the SQL server, c) "TheDateProperty" is a specific date field or property of a custom object

 //Call this when the form Loads private void AllowTheDatePickersToBeSetToNothing() { //This let you set the DatePicker to nothing dtp_X.CustomFormat = " "; dtp_X.Format = DateTimePickerFormat.Custom; } // Call this when Uploading or Adding the record (_NewRecord) to an SQL database private void Set_The_Field_Value_based_on_the_CustomFormat_of_the_DateTimePickers() { if (dtp_X.CustomFormat == " ") { //the date should be null _NewRecord.TheDateProperty = SqlDateTime.Null; } else { _NewRecord.TheDateProperty = SqlDateTime.Parse(Convert.ToString(dtp_X.Value)); } } //This button resets the Custom Format, so that the user has a way to reset the DateTimePicker Control private void btn_Reset_dtp_X_Click(object sender, EventArgs e) { dtp_X.Format = DateTimePickerFormat.Custom; dtp_X.CustomFormat = " "; } 
0
source share

All Articles