2014-12-02 26 views
0

我做了一個註冊頁面,用戶在其中輸入個人信息來創建一個帳戶。但我一直得到一個異常,我的應用程序與控制驗證根本不起作用!日期時間例外

protected void btnSubmit_Click(object sender, EventArgs e) 
{ 
    Registration _m = new Registration(); 
    DateTime dateOfBirth = DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", null); 
    lblMsg.Text = _m.Register(txtUser.Text, txtTitle.Text, txtPass.Text, 
    txtMidI.Text, txtSur.Text, txtCity.Text, txtPostCode.Text, txtxMobile.Text, 
    txtLandL.Text, txtEmail.Text, RBLMF.SelectedValue, dateOfBirth, 
    RBLYesNo.SelectedValue, txtSQ.Text, txtxAn.Text); 
} 

異常說:

String was not recognized as a valid DateTime. 
+1

什麼是你試圖解析日期時間字符串? – Icepickle 2014-12-02 23:20:59

+1

對於初學者,您應該使用調試器或堆棧跟蹤來查找代碼失敗的位置,儘管在這種情況下,它很可能是您對「DateTime.ParseExact」的單個調用。您嘗試創建日期的字符串不符合預期的格式。你使用什麼字符串? – cost 2014-12-02 23:22:39

+0

出生日期可以插入文本框內dd/MM/yyyy – chris 2014-12-02 23:22:57

回答

3

它看起來像你從字符串到日期的轉換失敗。由於您是從文本框中提取這些數據,這意味着輸入在理論上可能是任何東西,所以您應該始終驗證它。看看DateTime.TryParseExact。我沒有測試此代碼,但大概你想要做的是改變

DateTime dateOfBirth = DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", null); 

DateTime dateOfBirth; 
if (DateTime.TryParseExact(txtDOB.Text, "dd/MM/yyyy", null, DateTimeStyles.None, out dateOfBirth))) 
{ 
    //Do your logic in here 
    //..... 
} 
else 
{ 
    //Show a message to the user that they didn't enter a valid date 
    //..... 
} 
-2

使用 「d/M/YYYY」 更靈活,因爲它允許用戶進入個位數的月和日。

+0

這對OP有幫助嗎?當一天是2位數字時會發生什麼??該操作員想用'dd'格式化而不是'd' – MethodMan 2014-12-02 23:30:39

+0

@DJKRAZE它有點幫助。「d/M/yyyy」掩碼也接受「30/11/2014」但是,這應該由TryParseExact來處理 – Steve 2014-12-02 23:36:48