2012-03-31 128 views
0

我想將日期值的YYYY/MM/DD從文本框轉換爲日期時間,當值正確時它可以,但是當我嘗試輸入一個不正確的數據來檢查數據庫,錯誤返回爲String未被識別爲有效的DateTime。DateTime.Parse將字符串轉換爲日期時間格式等於數據庫中的日期時間字段

這裏是我的代碼:

protected void btnSubmit_Click(object sender, EventArgs e) 
    { 
     string format = "YYYY-MM-DD HH:MM:SS"; 
     DateTime birthday = DateTime.Parse(txtBday.Text); 
     DataSet ds = new DataSet(); 
     ds = (newService.checkAccount()); 
     if (ds.Tables[0].Rows.Count > 0) 
     { 
      foreach (DataRow dRow in ds.Tables[0].Rows) 
      { 
       string accountNo = dRow["ACCTNO"].ToString(); 
       DateTime birthDate = DateTime.Parse(dRow["DATEOFBIRTH"].ToString()); 
       if (accountNo == txtAccountNo.Text.ToString() && birthDate == birthday) 
       { 
        lblMessage.Text = "<br>Account Number Exist. You may now proceed with the registration<br><br>"; 
        HttpCookie lmsCookie = new HttpCookie("id"); 
        lmsCookie.Value = txtAccountNo.Text; 
        Response.Cookies.Add(lmsCookie); 
        Response.Redirect("Step2.aspx"); 
       } 
       else 
       { 
        Image2.Visible = false; 
        lblMessage.Text = "<br>Please check your information and try again." + "<br>Be sure you are entering the correct information.For further assistance, call (+632) 404-2790.<br><br>"; 
       } 
      } 
     } 
    } 

例如,我將進入數據將在數據庫匹配,程序會以其他方式進行,如果我要輸入不帶任何的匹配數據數據庫中的現有記錄,程序將觸發錯誤,字符串未被識別爲有效的日期時間。

回答

3

當你解析可能會失敗,而不是這是有原因的其他不是一個錯誤,:

DateTime birthDate = DateTime.Parse(dRow["DATEOFBIRTH"].ToString()) 

(它拋出,你見過一個例外),使用DateTime.TryParse

DateTime birthDate; 
if (DateTime.TryParse(dRow["DATEOFBIRTH"].ToString(), out birthDate)) 
{ 
    // Success case 
} 
else 
{ 
    // Handle error case 
} 

我注意到,你不是使用你的format變量,順便說一下。如果你知道是什麼格式將是(和你的問題不同意你的代碼,順便說一句),這將是更好地使用TryParseExact

if (DateTime.TryParseExact(dRow["DATEOFBIRTH"].ToString(), "YYYY/MM/dd", 
          CultureInfo.InvariantCulture, DateTimeStyles.None, 
          out birthDate)) 
... 
+0

喬恩,固定名稱的TryParse - > TryParseExact – asktomsk 2012-03-31 07:34:44

+0

@asktomsk:衛生署:)完成。 – 2012-03-31 07:36:24

+0

你能簡單解釋一下還是給我一個示例代碼來做這件事? – Dhenn 2012-03-31 07:38:39

0

肯定地說,它會拋出一個異常時,不支持的格式是試圖轉換成日期時間。所以,在轉換之前,您應該使用DateTime.TryParse方法解析它。

0

Sovel,

步驟1:

this._checkInOutDTO.NgayCham = DateTime.Parse(this.DGVDuLieuVaoRa.Rows [num15] .Cells [1] .Value.ToString()); // this._checkInOutDTO.NgayCham = Convert.ToDateTime(this.DGVDuLieuVaoRa.Rows [num15] .Cells [1] .Value.ToString());

步驟2: 格式:DD/MM/YYYY

相關問題