2012-06-07 19 views
-2

//嗨!我面臨的一個問題,每當我嘗試使用的DatePicker使用C#將Date(DatePicker)插入到SQL中#

插入日期
 DateTime birth_date=Convert.ToDateTime(datePickerEBirthDate.SelectedDate); 
      SqlConnection SQLconnection = new SqlConnection(@"Server=MyMachineName\SQLEXPRESS;Database=MyDataBase;Integrated Security=SSPI"); 
      SqlCommand command = SQLconnection.CreateCommand(); 
      SQLconnection.Open(); 
      command.CommandText = "INSERT INTO courses " + 
      "(name, birthdate) VALUES " + 
      "(@name, @birthdate)"; 
      command.Parameters.AddWithValue("@name", txtName.Text); 
      command.Parameters.AddWithValue("@birthdate", birth_date); 
      command.ExecuteNonQuery(); 
     SQLconnection.Close(); 

//這是錯誤消息 enter image description here

+1

使用visual studio斷點並調試代碼。查看birth_date變量中的值是什麼? – Shyju

+0

這對你有用嗎? [http://stackoverflow.com/questions/2191120/net-datetime-to-sqldatetime-conversion][1] [1]:http://stackoverflow.com/questions/ 2191120 /淨日期時間至SQLDATETIME轉換 –

+0

值在birth_date變量{1/1/0001 12:00:00 AM}來 – Yasser

回答

1

就像你搶TextBox.Text屬性(txtName.Text),你應該抓住DatePicker.SelectedDate財產(dpSBirthDate.SelectedDate)。相反,您正嘗試將DataContext轉換爲某種原因?此外,你可以擺脫Convert.ToDateTime(...)調用,因爲dpSBirthDate.SelectedDate將返回一個DateTime對象。


UPDATE(這裏是一個完全搞掂代碼段):

var name = txtName.Text; 
var birthdate = dpSBirthDate.SelectedDate; 

using (var connection = new SqlConnection(@"Server=MyMachineName\SQLEXPRESS;Database=MyDataBase;Integrated Security=SSPI") 
using (var command = connection.CreateCommand()) 
{ 
    command.CommandText = "INSERT INTO courses " + 
          "(name, birthdate) VALUES " + 
          "(@name, @birthdate)"; 

    if (name == null) 
     throw new Exception("Name cannot be null."); 
    if (!birthdate.HasValue) 
     throw new Exception("Birthdate must contain a value."); 

    command.Parameters.AddWithValue("@name", name); 
    command.Parameters.AddWithValue("@birthdate", birthdate.Value); 
    connection.Open(); 
    command.ExecuteNonQuery(); 
} 

現在,如果這個代碼失敗,它會告訴你爲什麼...無論你的名字或出生日期無效。如果出生日期仍然無效,那麼在執行此代碼之前,您必須檢查dpSBirthDate(DatePicker)是否設置爲正確的DateTime。希望有所幫助。

另外請注意,我加入using語句,異常處理和儘可能晚地打開連接清理代碼。

+0

我試圖DateTime的出生日期= Convert.ToDateTime(datePickerEBirthDate.SelectedDate); – Yasser

+0

並給出了相同的輸出{1/1/0001 12:00:00 AM} – Yasser

+0

雖然它不應該有所作爲,擺脫Convert.ToDateTime的。這是沒有必要的。 –

0

日期時間在.NET可以從0001 1月1日十二月9999存儲日期至31在SQL 1月1日1753年至1731年十二月9999所以,揚0001和1753年1月1日之間的日期1不能被保存到數據庫中。所以,檢查分析的birth_date。可能你必須用正確的文化解析日期嗎?

0

你應該使用datePickerEBirthDate.Value,它會給你日期時間類型,所以不需要轉換爲DateTime,但你最終會在這個時間結束,並可能不希望通過這個搜索,但這是你的偏好。

+0

我試過了,但它給出了一個運行時錯誤:可爲空的對象必須有一個值。 – Yasser

+0

您使用WPF是在這種情況下使用不同的datePickerEBirthDate.SelectedDate井corrent,但你必須確保它有一個日期,開始時,你可以解決這個問題通過在window_loaded事件設置defualt日期即datePickerEBirthDate.SelectedDate = DateTime。現在; SelectedDate是一個可爲空的值類型,這意味着它不包含該值,因此您可以使用它來查看它是否首先由if(datePickerEBirthDate.SelectedDate!= null){DateTime birth_date = datePickerEBirthDate.SelectedDate.Value;}幫助:) – Troublesum