0

希望你做得好。

我有列表框,我想分配主键和一个文本(例如学生表)。所以我写了这段代码。

    mySQLCmd.CommandText = "SELECT studentname, studentid FROM studentstable WHERE Year(DOB) = " + selectedYear
    Dim dt As New DataTable
    myReader = myCmd.ExecuteReader()
    dt.Load(myReader)
    Listbox1.datavaluefield = "studentid"
    Listbox1.datatextfield = "studentname"
    ListBox1.DataSource = dt
    ListBox1.DataBind()

列表框工作正常。SQL 语句工作正常。我想在 ListBox1_SelectedIndexChanged 上捕获 selectedvalue 和 selecteditem 属性

    1. Dim selectedPupil As String = ListBox1.SelectedItem.ToString()
    2. Dim selectedPupilID As Integer = ListBox1.SelectedValue

当我在列表框中选择某些内容时, selecteditem 和 selectedvalue 属性都只返回学生姓名,而不是学生 ID。所以我得到这个错误。

    Error on Line2. Conversion from string "RichardCole" to type 'Integer' is not valid.

我不知道为什么?所以我要找回学生的价值吗?我需要知道 ID 因为名称不能用作 PK 所以。

非常感谢。

4

2 回答 2

3

您在 listbox1 上设置了值和文本字段,但您将数据绑定到 listbox2。所以,除非我遗漏了其他东西,否则这似乎是问题所在。

listbox1 在哪里填充/绑定?

于 2012-02-09T13:13:30.880 回答
1
  mySQLCmd.CommandText = "SELECT studentname, studentid FROM studentstable WHERE Year(DOB) = " + selectedYear
Dim dt As New DataTable
myReader = myCmd.ExecuteReader()
dt.Load(myReader)
Listbox2.DataValueField = "studentid"    'it was ListBox1 now ListBox2
Listbox2.DataTextField = "studentname"   'it was ListBox1 now ListBox2
ListBox2.DataSource = dt
ListBox2.DataBind()

另一件事是使用 ListBox2 而不是一个已

更新

  Dim selectedPupil As String = ListBox2.SelectedItem.Text.ToString()
Dim selectedPupilID As Integer = Ctype(ListBox2.SelectedValue, Integer) 'convert the value to integer

或将变量设为字符串

  Dim selectedPupilID As String = ListBox2.SelectedValue

或者把上面所有的 ListBoxes 都改成ListBox1,但是不要这样混

于 2012-02-09T13:28:48.027 回答