2013-10-30 42 views
0

嘿傢伙我一直在努力解決這個問題,但我試圖添加一個新的用戶到學生表,我不斷收到錯誤:轉換將nvarchar數據類型轉換爲日期時間數據類型會導致超出範圍值。試圖添加一個新的記錄到一個表在asp.net

這是我的代碼,我認爲它與dob變量有關。我使用Visual Studio 2010中

SqlConnection insertStu = new SqlConnection(ConString()); 

    insertStu.Open(); 

    string dataStu = "INSERT INTO [Student] ([fName], [lName], [dob], [gender], [address], 
    [suburb], [postcode], [username], [parentName], [parentContact]) VALUES (@fName, @lName, 
    @dob, @gender, @address, @suburb, @postcode, @username, @parentName, @parentContact)"; 

    SqlCommand insertStuData = new SqlCommand(dataStu, insertStu); 

    insertStuData.Parameters.AddWithValue("@fName", given.Text); 
    insertStuData.Parameters.AddWithValue("@lName", surname.Text); 
    insertStuData.Parameters.AddWithValue("@dob", dob.Text); 
    insertStuData.Parameters.AddWithValue("@gender", gender.Text); 
    insertStuData.Parameters.AddWithValue("@address", address.Text); 
    insertStuData.Parameters.AddWithValue("@suburb", suburb.Text); 
    insertStuData.Parameters.AddWithValue("@postcode", postcode.Text); 
    insertStuData.Parameters.AddWithValue("@username", given.Text + surname.Text); 
    insertStuData.Parameters.AddWithValue("@parentName", pname.Text); 
    insertStuData.Parameters.AddWithValue("@parentContact", phone.Text); 
    insertStuData.ExecuteNonQuery(); 
    Response.Redirect("login.aspx"); 

感謝您的幫助傢伙我固定它使用以下

DateTime bday = Convert.ToDateTime(dob.Text); 

,並在變量收集我做了以下

insertStuData.Parameters.AddWithValue("@dob", bday); 

這是理想嗎,我應該做其他事嗎?

+1

它期待您傳遞'DateTime'對象而不是'String'。 –

回答

0
insertStuData.Parameters.AddWithValue("@dob", dob.Text); 

可能造成的問題,確保dob.Text是DateTime類型 不知道你的表結構,我只是猜測

+1

你應該嘗試DateTime dt = new DateTime(1980,1,1);並用dt替換dob.Text – lostincomputer2

0

如前所述你使用它需要一個日期的字符串。使用以下,當然有適當的例外。

insertStuData.Parameters.AddWithValue("@lName", surname.Text); 
/* New Code */ 
DateTime birthDate = new DateTime(); 
if(DateTime.TryParse(dob.Text, out birthDate))  
{ 
    insertStuData.Parameters.AddWithValue("@dob", birthDate); 
} 
else 
{ 
    throw new Exception("Date incorectly formatted"); 
    /*Or However you want to handle the incorectly formatted date*/ 
} 
/* End New Code*/ 
insertStuData.Parameters.AddWithValue("@gender", gender.Text); 

如果你絕對100%知道的日期將被正確的格式,你可以使用DateTime.Parse代替,而不需要額外的變量和if..else..聲明。

相關問題