无法解决为注册而抛出的异常错误



我现在正在注册,如果用户将他们放在18岁以下-在他们提交注册后会出现错误,说You must be at least 18 years of age.,但我一直在提交表中的调用堆栈中抛出这个异常错误,说string was not recognized as a valid。我已经把BirthDate.Text = DateTime.Now.ToString("dd/MM/yyyy");尝试和修复解决方案,但错误仍然出现作为一个例外。我是不是错过了什么?

问题中的错误是

if (DateTime.Parse(BirthDate.Text).AddYears(18) > DateTime.Now) {
errorList.Add("You must be at least 18 years of age.");

的代码
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace website {
public partial class Register : Page {
string ConnectionString = "Server=localhost\SQLEXPRESS;Database=HC;Trusted_Connection=True;";
protected void Page_Load(object sender, EventArgs e) {
BirthDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
if (!IsPostBack) {
string QueryString = "select * from home";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter myCommand = new SqlDataAdapter(QueryString, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "House");
}
}
protected void submit(object sender, EventArgs e) {
List<string> errorList = new List<string>();
if (BirthDate.Text == "") {
LiteralControl birthDate = new LiteralControl("Birth date is required!");
BirthDateRequired.Controls.Add(birthDate);
errorList.Add(birthDate.Text);
}
if (DateTime.Parse(BirthDate.Text).AddYears(18) > DateTime.Now) {
errorList.Add("You must be at least 18 years of age.");
}
if (errorList.Count > 0) {
foreach (string s in errorList)
ErrorList.Controls.Add(new LiteralControl("* " + s));
}
}
}
}

您可以使用以下ParseExact方法的重载-

public static DateTime ParseExact(string s, string format, IFormatProvider? provider);

,您可以将预期的日期格式作为字符串传递给第二个参数。

因此,如果您的BirthDate.Text正在接受dd/MM/yyyy格式的输入,那么将代码更改为-

if (DateTime.ParseExact(BirthDate.Text, "dd/MM/yyyy", null).AddYears(18) > DateTime.Now)
{
errorList.Add("You must be at least 18 years of age.");
}

同样,你不需要设置BirthDate.Text = DateTime.Now.ToString("dd/MM/yyyy");

最新更新