【发布时间】:2019-10-18 18:01:35
【问题描述】:
对于我的家庭作业,我要向用户询问:姓名和出生日期(月、日、年作为他们自己的文本框)。然后计算他们的年龄。如果输入不正确,例如空字段和月份的不正确日期(例如月份字段不应为 0 或大于 12),我还必须显示错误。我有一个基本测试: if (dayTextBox.Text > 31 || dayTextBox.Text
我一直在使用标签来显示错误。这行得通。但是,当我检查空或空字段时,程序崩溃。如果不检查空字段,程序就可以正常工作而不会崩溃。我试图把这个 if 检查放在其他检查之上(它们都在 if、if else 系列语句中)以及将每个将 TextBox.Text(s) 更改为 DateTime 格式的字段的变量之前计算年龄。
if (string.IsNullOrEmpty(NameOutputLabel.Text) || string.IsNullOrEmpty(MonthDOBTextBox.Text) || string.IsNullOrEmpty(DayDOBTextBox.Text) || string.IsNullOrEmpty(YearDOBTextbox.Text))
{
AgeOutputLabel.Text = "Cannot have empty fields";
}
这里的参考是我的其他检查的一个例子
if (month < 1 || month > 12)
{
AgeOutputLabel.Text = "Invalid month. Must be between 1 and 12";
}
这就是我的 DateTime 的设置方式:
int year = Convert.ToInt32(YearDOBTextbox.Text);
int month = Convert.ToInt32(MonthDOBTextBox.Text);
int day = Convert.ToInt32(DayDOBTextBox.Text);
// This sets the calculation for determining the age
DateTime currentDate = DateTime.UtcNow;
DateTime usersBirthDate = new DateTime(year, month, day);
int age = currentDate.Year - usersBirthDate.Year;
只想检查空字段和空字段,以及检查日、月、年的正确输入。一直显示正确的错误(字段不能为空 || 月份必须介于 1 和 12 之间,等等)
【问题讨论】:
-
如果您的程序崩溃,那么您应该会收到一条错误消息,说明问题所在。你能edit你的问题并添加这条消息吗?
-
如果没有通过检查,也许您想取消进一步的操作?您可以尝试将
return;添加到您的代码中。
标签: c# validation