将DateTimePicker设置为Null

7

我无法将Datetimepicker设置为Null,该怎么办?在我的项目中,我的要求是验证DTP是否为空,为此我需要将其设置为Null。我使用的代码是:

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

6
使用以下代码:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";

4

当DateTimePicker的值发生变化时,取一个变量并设置它的值。

例如:

DateTime? myselectedDate = null;

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

3

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

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

0

就像“karthik reddy”上面提到的,您需要使用“CustomFormat”,但是为了将null写回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 = " ";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接