7

我无法将 Datetimepicker 设置为 Null,该怎么做。在我的项目中,我的要求是验证 DTPif 它是否为空,因为我需要设置为空,我使用的代码是:

              {
                dateInsert.Format = DateTimePickerFormat.Custom;
                dateInsert.Text = string.Empty;
               }
4

4 回答 4

6

使用以下代码:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
于 2013-09-12T06:07:17.800 回答
4

当 DateTimePicker 值改变时取一个变量并设置它的值

例如

DateTime? myselectedDate = null;

private void DateTimePicker1_ValueChanged(Object sender, EventArgs e) {
   myselectedDate = DateTimePicker1.Value;
}
于 2013-09-12T06:05:45.480 回答
3

我有一个类似的问题,但我找不到我喜欢的答案。不过,我确实想出了一个合适的解决方案。将 datetimepicker 的“ShowCheckBox”属性设置为 true。这将在框中的日期旁边放置一个复选框。然后添加以下代码。

if (dateTimePicker1.Checked == false) 
    myVariable = ""; 
else 
    myVariable = dateTimePicker1;
于 2014-04-16T23:20:37.010 回答
0

就像上面提到的“karthik reddy”一样,您需要使用“CustomFormat”,但是要将空值写回 SQL 数据库(例如),您的代码必须在“添加”或“更新”记录时检查 DateTimePicker,所以你至少需要两段代码。其中 a) 'dtp_X' 是 DateTimePicker 控件,b) '_NewRecord' 是发送回 SQL 服务器的自定义对象,c) 'TheDateProperty' 是自定义对象的特定日期字段或属性

//Call this when the form Loads 
private void AllowTheDatePickersToBeSetToNothing()      
{
//This let's 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 = " ";
}
于 2014-10-31T14:15:39.657 回答