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

标签 c# winforms entity-framework data-binding

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

相关文章:

c# - 如何在我的业务逻辑层中管理统一性?

c# - 不等待时出现 TaskCanceledException

c# - 使用 Entity Framework 中的附加字段建模多对多关系

c# - 当 DataGridView.SelectionMode 为 FullRowSelect 时剪贴板复制失败

.net - 无法将 Generic.List<AnonymousType#1> 转换为 Generic.List<BillEF.Bill>

c# - Xamarin 表格 : Check if user inactive after some time log out app

c# - 在 C# WinForms 中预览文档(Word、Excel、PDF、文本文件等)?

c# - 查找 Deepest child Treenode 的层级

c# - 在 Entity Framework 6 中什么时候不需要声明关系?

c# - Entity Framework 代码首先使列不可为空