将DateTimePicker设置为Null

时间:2013-09-12 05:58:20

标签: c# datetimepicker

我无法将Datetimepicker设置为Null,怎么做呢。在我的项目中,我的要求是验证DTP如果它是null,因为我需要设置为Null,我使用的代码是:

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

4 个答案:

答案 0 :(得分:6)

使用以下代码:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";

答案 1 :(得分:4)

获取变量并在DateTimePicker值更改时设置其值

e.g。

DateTime? myselectedDate = null;

private void DateTimePicker1_ValueChanged(Object sender, EventArgs e) {
   myselectedDate = DateTimePicker1.Value;
}

答案 2 :(得分:3)

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

if (dateTimePicker1.Checked == false) 
    myVariable = ""; 
else 
    myVariable = dateTimePicker1;

答案 3 :(得分: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 = " ";
}
相关问题