如何获取列表框vb.net的选定值字段
希望你做得好。
我有列表框,我想分配主键和文本(例如学生表)。所以我写了这段代码。
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.
我不知道为什么?那么我要拿回 Studentid 值吗?我需要知道 ID,因为名称不能用作 PK。
非常感谢。
Hope u r doing well.
I have Listbox, that I want to assign primary key, and a text (eg. students table). So i wrote this code.
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()
The listbox works fine. SQL statement works fine. And I want to catch selectedvalue and selecteditem properties on ListBox1_SelectedIndexChanged
1. Dim selectedPupil As String = ListBox1.SelectedItem.ToString()
2. Dim selectedPupilID As Integer = ListBox1.SelectedValue
When I select something on the listbox, both of selecteditem and selectedvalue properties just return the student name, not the student id. So I get this error.
Error on Line2. Conversion from string "RichardCole" to type 'Integer' is not valid.
I don't know why? So i do i get the studentid value back ? I need to know the ID coz name can't use as PK so.
Thanks so much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在 listbox1 上设置值和文本字段,但将数据绑定到 listbox2。所以,除非我遗漏了其他东西,否则这似乎可能是问题所在。
listbox1 在哪里填充/绑定?
You set the value and text fields on listbox1 but you are binding the data to listbox2. So, unless I am missing something else, that seems like it could be the problem.
Where is listbox1 filled/bound?
另一件事是使用 ListBox2 而不是一个
更新:
或者将变量设置为字符串
或者将上述所有ListBox更改为
ListBox1
,但不要以这种方式混合它们The other thing is use ListBox2 not one
Updated:
or make the variable a string
Or change all the above ListBoxes to
ListBox1
, but don't mix them this way