我正在爲我的部門開發一個應用程序。我遇到了一個大問題。Linq中的InvalidCastException實體查詢
我想獲得在ListBox控件上選擇的名稱的主鍵。該表單加載時,該數據庫中的查詢將填充此ListBox控件。以下是用於填充ListBox控件的查詢。
Dim examinationOfficer As New ExamOfficerPayEntities
Dim findOfficer = From officer In examinationOfficer.Exams_Officer
Order By officer.First_Name Ascending
Select officer.First_Name.ToUpper & " " & officer.Last_Name.ToUpper
lstFullname.DataSource = findOfficer.ToList
lstFullname.DisplayMember = "FullName"
該查詢工作正常,並按預期方式填充列表框。問題是我想獲取所選列表框項目的主鍵的值。我試圖檢索的主鍵值是一個整數值,它被設置爲identity
。
下面是我的數據庫的摘要。
表Exam_Officer
:
Officer_ID as int which is the primary key and is also set as an identity column
First_Name as nvarchar
last_Name as nvarchar
另外一個表是Result_Submitted
, 其列:
sn as integer primary key and an identity column
Officer_ID as an int and is a foreign key to the Table Exam_Officer
Result_Submitted as nvarchar
Outstanding_Result as nvarchar
這是我試圖使用從的SelectedItem
財產得到officer_ID
代碼Windows窗體的ListBox控件。
Dim selectedOfficer As Exams_Officer = DirectCast(lstFullname.SelectedItem, Exams_Officer)
Dim selectedOfficerID As Integer = selectedOfficer.Officer_ID
The code dosen't work it throws an error on the first line (directcast method)
System.InvalidCastException was unhandled
Message=Unable to cast object of type 'System.String' to type 'EXAMINATION_OFFICER_PAYMENT.Exams_Officer'.
Source=EXAMINATION OFFICER PAYMENT
我很困惑,不知道還有什麼要做。任何幫助表示讚賞。
謝謝先生,我已經完成了你所說的。現在的錯誤是無法投射'VB $ AnonymousType_0'2'類型的對象[System.String,EXAMINATION_OFFICER_PAYMENT.Exams_Officer]'來鍵入'EXAMINATION_OFFICER_PAYMENT.Exams_Officer'。請現在我可以訪問官員對象的所有屬性,但是當我做直播時,它仍然拒絕獲得officer_ID屬性。我是一個noob,在這我仍然在學習。感謝你的所有努力。 –
@JamesOshomah:這表明你實際上並沒有像最後一句中所說的那樣提取「官」屬性。 –
請你能告訴我怎麼去做。老實說我不知道該怎麼做。謝謝,願上帝保佑你爲你付出的時間和精力 –