繁体   English   中英

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

[英]Cannot resolve exception error thrown for registration

我现在正在注册,如果用户说他们未满 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.Textdd/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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM