簡體   English   中英

如何獲取列表框vb.net的選定值字段

[英]how to get the selected value field of listbox vb.net

希望你一切都好。

我有列表框,我想分配主鍵,以及一個文本(例如,students表)。 所以我寫了這段代碼。

    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 Coz名稱不能用作PK。

非常感謝。

您在listbox1上設置了value和text字段,但是將數據綁定到listbox2。 因此,除非我缺少其他東西,否則可能就是問題所在。

listbox1在哪里填充/綁定?

  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 ,但不要這樣混合使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM