我正在为我的部门申请工作。我遇到了一个大问题。
我正在尝试获取在 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"
查询工作正常,ListBox 已按预期填充。问题是我正在尝试获取所选 ListBox 项的主键的值。我试图检索的主键值是一个整数值,它被设置为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
这是我试图用来officer_ID
从SelectedItem
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
我很困惑,不知道还能做什么。任何帮助表示赞赏。