0

我正在为我的部门申请工作。我遇到了一个大问题。

我正在尝试获取在 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_IDSelectedItemWindows 窗体的 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

我很困惑,不知道还能做什么。任何帮助表示赞赏。

4

2 回答 2

1

老实说,我很惊讶它现在甚至显示,因为FullName它不是String. 看看你的代码:

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

您正在选择全名 - 因此您的代码结果只是名称,而不是原始官员。我怀疑你想要:

Dim examinationOfficer As New ExamOfficerPayEntities
Dim findOfficer = From officer In examinationOfficer.Exams_Officer
                  Order By officer.First_Name Ascending

lstFullname.DataSource = findOfficer.ToList
lstFullname.DisplayMember = "FullName"

那时,您得到的是官员列表,而不是字符串列表。这是假设FullName是您的军官类型的财产。如果不是,您可能希望投影到一个列表,在该列表中您在一个属性中进行字符串连接,但将原始官员保留在另一个属性中。例如:

Dim examinationOfficer As New ExamOfficerPayEntities
Dim findOfficer = From officer In examinationOfficer.Exams_Officer
    Order By officer.First_Name Ascending
    Select New With {
        .FullName = officer.First_Name.ToUpper & " " _ & officer.Last_Name.ToUpper,
        .Officer = officer
    }

lstFullname.DataSource = findOfficer.ToList
lstFullname.DisplayMember = "FullName"

稍后,您需要提取Officer属性的值以获取官员对象本身。

于 2013-06-01T13:12:56.843 回答
0

通常,执行此操作的方法是将官员添加到您的 ListBox 并覆盖官员的 ToString() 方法以返回 FullName,或绑定并将 DisplayMember 设置为 Fullname。像 Jon Skeet 一样,我不确定您发布的代码为什么有效......

然后你可以做

Dim selectedOfficer As Exams_Officer = DirectCast(lstFullname.SelectedItem, Exams_Officer)

Exams_Officer.OfficeID没事的。

在您将字符串投射到官员的那一刻,上面将对象投射到官员,这更有可能起作用。

但是请记住,您需要实例化您的所有军官,并且他们将在内存中。因此,如果有很多和/或官员是一个沉重的对象,性能可能会开始受到影响。那时最简单的选择是一个小类/结构,其中只有 ID 和名称。

于 2013-06-01T13:38:19.717 回答