【发布时间】:2019-05-18 23:21:43
【问题描述】:
我在 DateTime (DateofBirth) 和 int (TelephoneNumber) 字段中弹出错误。
目前正在做一个简单的图书馆应用程序来在图书馆内注册新的客户记录 - 尝试实施验证,以便在单击“保存”按钮(创建新记录)时检查字段以查看数据是否已提交到其中。
例如。我在 NAME 字段中使用了下面的代码,它工作正常。
下面是 DateofBirth 和 TelephoneNumber 字段,我实现了类似于 Name 的代码,但是,它们不起作用(我收到错误)。我还是 C# 的新手,非常感谢您的帮助。
非常感谢。
有效的示例。
Name = this.txtName.Text;
if (string.IsNullOrWhiteSpace(Name))
{
MessageBox.Show("Customer's name is required. Please do not leave this field empty.");
using (var erp_provider = new ErrorProvider())
erp_Provider.SetError(this.txtName, "Customer's name is required. Kindly submit the details in the given field.");
return;
}
///// 以下代码的问题:
DateofBirth = DateTime.Parse(msktxtDateofBirth.Text);
if (DateofBirth == DateTime.MinValue)
{
MessageBox.Show("Customer's Date of Birth is required. Please do not leave this field empty.");
using (var erp_provider = new ErrorProvider())
erp_Provider.SetError(this.msktxtDateofBirth, "Customer's Date of Birth is required. Kindly submit the details in the given field.");
return;
}
TelephoneNumber = Convert.ToInt32(txtTelephoneNumber.Text);
if (TelephoneNumber == null)
{
MessageBox.Show("Customer's Telephone Number is required. Please do not leave this field empty.");
using (var erp_provider = new ErrorProvider())
erp_Provider.SetError(this.txtTelephoneNumber, "Customer's Telephone Number is required. Kindly submit the details in the given field.");
return;
}
出生日期错误:
(异常未处理) System.FormatException: '字符串未被识别为有效的日期时间。'
电话号码错误:
(异常未处理) System.FormatException: '输入字符串的格式不正确。'
【问题讨论】:
-
使用 TryParse 方法集查看用户输入是否对数据类型有效。例如 Convert.ToInt32("") 引发该异常。 DateTime.Parse 也会发生同样的情况,并且该字符串不是您的文化设置的有效日期
-
抱歉,我还是个编程菜鸟——请问您是这个意思吗? DateofBirth = DateTime.Parse(msktxtDateofBirth.Text);
-
谢谢@Steve,效果很好(如下所示) bool isGoodDate = DateTime.TryParse(msktxtDateofBirth.Text, out DateofBirth); if (DateofBirth == DateTime.MinValue) Integer (TelephoneNumber) 也需要相同的值吗?
-
我已经发布了答案。请注意,您不需要检查 DateTime.MinValue 或 null。 TryParse 将为您提供驱动逻辑所需的布尔结果。
标签: c# validation datetime integer