gpt4 book ai didi

c# - 如何将空白文本框值作为 null 传递给绑定(bind)日期时间

转载 作者:行者123 更新时间:2023-11-30 21:08:10 25 4
gpt4 key购买 nike

根据标签,这是一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com