C# BindingSource with DateTime Field-value with different format then Db not able to save

C# BindingSource with DateTime Field-value with different format then Db not able to save

我的数据源中有一些日期字段我想在屏幕上的文本框中以不同的格式设置这些日期的格式,然后将它们存储在数据库中。我还希望用户能够以这种格式更改日期。但这是不可能的。文本框不接受输入的日期。

我使用的文本框中的格式:

tbSysDateFrom.DataBindings.Add("Text", myBindingSource, "SysDateFrom", true, DataSourceUpdateMode.OnValidation, "", "dd-MM-yyyy");

这行得通。但是当用户尝试输入日期时,即 23-12-2015 文本框不会接受它。我可以理解这一点,因为在此示例中,数据库中的格式为 MM/dd/yyyy,数据源认为 23 是月份值。

我在 GridView 中呈现数据时遇到了同样的问题。我可以将日期格式化为 dd-MM-yyyy,但用户被迫以类似 MM-dd-yyyy

的格式输入日期

我不确定如何解决这个问题,所以有没有人有想法。也许覆盖一些方法?但哪些是什么时候?谁能告诉我正确的方向?

B.t.w。我必须使用文本框(不能使用日期选择器)

[更新]

好的,我想出了如何解决文本框的这个问题。我通过使用以下代码为文本框添加验证事件来做到这一点:

 private void tbSysDateTo_Validating(object sender, CancelEventArgs e)
    {
        DateTime dateValue;

        if (!String.IsNullOrEmpty(tbSysDateTo.Text))
        {
            if (DateTime.TryParseExact(tbSysDateTo.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
                tbSysDateTo.Text = String.Format("{0:MM/dd/yyyy}", dateValue);
        }
    }

这行得通,现在我必须对 gridview 做同样的事情。在这里,我仍然被困住了。当我在 CellValidating 事件中更改格式时,我在绑定源想要保存日期时收到错误消息。

错误与日期有关:"String was nog recognized as a valid DateTime"。

有什么解决这个问题的建议吗? TIA

好的,我能够解决我的问题。首先是 TextBox 问题(顺便说一句,所有控件都使用 BindingSources 绑定):

TextBox 的格式必须为 dd-MM-yyyy。为此,我像这样

添加了对 TextBox 的绑定
tbSysDateTo.DataBindings.Add("Text", myBindingSource, "SysDateTo", true, DataSourceUpdateMode.OnValidation, "", "dd-MM-yyyy");

这工作正常,但是当我试图保存日期时,由于格式错误而抛出异常。我能够通过在此 TextBox 的验证事件中重新格式化 TextBox 的文本来解决此问题,例如:

private void tbSysDateTo_Validating(object sender, CancelEventArgs e)
{
    DateTime dateValue;

    if (!String.IsNullOrEmpty(tbSysDateTo.Text))
    {
        if (DateTime.TryParseExact(tbSysDateTo.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
            tbSysDateTo.Text = String.Format("{0:MM/dd/yyyy}", dateValue);
    }
}

至于 GridView,其中日期字段也显示为 dd-MM-yyyy 格式,我不得不做类似的事情。但我不知道使用哪个事件。 Row_Validation 或 Cell_validation 没有成功。

我最终使用了对我来说工作正常的 CellParsing 事件。

 private void dgv_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
    {
        DateTime dateValue;

        // Confirm that the cell is not empty.
        if (!string.IsNullOrEmpty(e.Value.ToString()))
        {
            if (DateTime.TryParseExact(e.Value.ToString(), "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
            {
                e.Value = dateValue;
                e.ParsingApplied = true;                
            }
        }
    }

参见:This For More info

(更正了更多信息中的link,因为MS显然又移动了内容)