2011-09-28 159 views
0

我正在將文本字段轉換爲日期時間並插入到數據庫中。然而,當文本字段爲空,則拋出如何解決「字符串未被識別爲有效的DateTime」?

字符串未被識別爲有效的DateTime

一個例外是我所做的:

nvpt4Entities db = new nvpt4Entities(); 

    ClassInfo order = new ClassInfo 
    { 
     ClassID = classID.Text, 
     ClassName = className.SelectedItem.Text, 
     ClassTime = classTime1.Text, 
     ClassDate = DateTime.ParseExact(classDate1.Text, "MM/dd/yyyy", null), 
     ClassDay = classDay.SelectedValue, 
     ClassMonth = classMonth.SelectedValue, 
     ClassLocation = classLocation.SelectedItem.Text, 
     ClassNotes= classNotes.Text, 
     ClassInstructor = classInstructor.SelectedValue, 
     ClassInstructor1 = classInstructor2.SelectedValue, 
     ClassInstructor2 = classInstructor3.SelectedValue, 
     MultiDate2 = DateTime.ParseExact(multidate2.Text, "MM/dd/yyyy", null), 
     MultiDate3 = DateTime.ParseExact(multidate3.Text, "MM/dd/yyyy", null), 
     MultiDate4 = DateTime.ParseExact(multidate4.Text, "MM/dd/yyyy", null), 
     MultiDate5 = DateTime.ParseExact(multidate5.Text, "MM/dd/yyyy", null), 
     ClassStrength = Convert.ToInt16(classStrength.Text), 
     ClassProvider = classProvider.SelectedItem.Text, 
     LocationID = Convert.ToInt16(classLocation.SelectedValue), 
     ClassCID = Convert.ToInt16(className.SelectedValue), 
     ProviderID = Convert.ToInt16(classProvider.SelectedValue) 

    }; 

所以,我想知道如何處理空字符串如果你的領域是你可以使用這個可空DateTime是否要轉換成datetime同時插入數據庫

+1

你想要什麼的空字符串轉換爲?這些可爲空的DateTime列嗎? – Jacob

+0

不,它們不是可以爲空的日期時間列 – user838359

+2

那麼應該將空字符串轉換爲什麼呢? – Jacob

回答

2

ClassDate = string.IsNullOrEmpty(classDate1.Text) ? (DateTime?)null : 
       DateTime.ParseExact(classDate1.Text, "MM/dd/yyyy", null), 
+0

現在我得到一個錯誤說空和日期時間 – user838359

+0

+1之間不存在隱式轉換,但如果你這樣做,你會得到一個編譯器錯誤,我相信。將'null'替換爲'(DateTime?)null'。 – Jacob

+0

@Jacob:哎呀,謝謝! –

3

這有沒有與數據庫有關。請注意錯誤消息以及發生異常的位置。相關的唯一的事情就是錯誤來源於:

DateTime.ParseExact(__, "MM/dd/yyyy", null) 

與處理「空/無效的字符串」的情況下適當的方法調用替換這一點,但是爲宜,使用驗證,以確保這一步永遠不會到達; DateTime?應該用於可空列,否則可以使用標記。 (見馬克拜爾斯什麼該方法的內容可能看起來像答案。)

編碼愉快。

相關問題