【发布时间】:2023-03-28 17:00:02
【问题描述】:
根据标签,这是一个实体框架、C#、Winforms 问题。
我有一个文本框数据绑定到我的实体中的可为空的日期时间字段。当我删除文本框的内容并将其留空时,我想将空值传递回实体。
文本框 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;
}
任何想法都会有所帮助。
【问题讨论】:
-
据我所知,您的行 txtDueDateDetail.Text = null 永远不会起作用,因为 TextBox 的 text 属性永远不会为空。如果您立即读回该值,您会得到一个空字符串,而不是 null。我将尝试绑定不同的属性(例如 Tag),并在验证事件中更新该属性,但我在这里停下来,因为我不知道如何使用 EF。
标签: c# winforms entity-framework data-binding