我想將日期值的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>";
}
}
}
}
例如,我將進入數據將在數據庫匹配,程序會以其他方式進行,如果我要輸入不帶任何的匹配數據數據庫中的現有記錄,程序將觸發錯誤,字符串未被識別爲有效的日期時間。
喬恩,固定名稱的TryParse - > TryParseExact – asktomsk 2012-03-31 07:34:44
@asktomsk:衛生署:)完成。 – 2012-03-31 07:36:24
你能簡單解釋一下還是給我一個示例代碼來做這件事? – Dhenn 2012-03-31 07:38:39