根据标签,这是一个 Entity Framework 、C#、Winforms 问题。
我有一个文本框数据绑定(bind)到实体中可为空的日期时间字段。当我删除文本框的内容并将其留空时,我想将空值传递回实体。
文本框 CausesValidation 属性 = true。当我删除文本框的内容时,如果不输入有效日期,我将无法保留它。
这是我的验证事件
private void txtDueDateDetail_Validating(object sender, CancelEventArgs e)
{
string errorMsg;
if (!ValidDate(txtDueDateDetail.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
txtDueDateDetail.Select(0, txtDueDateDetail.Text.Length);
// Set the ErrorProvider error with the text to display.
this.epNew.SetError(txtDueDateDetail, errorMsg);
}
Debug.Write("text: " + txtDueDateDetail.Text);
}
public bool ValidDate(string pTextDate, out string errorMessage)
{
DateTime tempDate;
errorMessage = "";
if (pTextDate.Length == 0)
{
//pass a null date...how?
return true;
}
DateTime.TryParse(pTextDate, out tempDate);
if (tempDate == DateTime.MinValue)
{
errorMessage = "date must be in format MM/dd/yyyy";
return false;
}
return true;
}
任何想法都会有帮助。
最佳答案
考虑到您最初的方法,您是否尝试设置 Binding.NullValue
空字符串?您可以通过编程方式执行此操作,如下所示:
txtDueDateDetail.DataBindings["Text"].NullValue = "";
根据 docs ,将空字符串分配给 NullValue
与分配 null
(这是其默认值)不同。
你的最终解决方案很好。在阅读 NullValue
属性之前,我考虑过实现它。对我来说,它的缺点是它降低了数据绑定(bind)的实用性,因为这样我最终会手动将更改后的值分配回数据源——并且我希望数据绑定(bind)能够为我做到这一点。
关于c# - 如何将空白文本框值作为 null 传递给绑定(bind)日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9830093/