vb.net – Listbox.selected索引更改变量赋值
发布时间:2020-12-17 07:18:15 所属栏目:百科 来源:网络整理
导读:嗨,您好 将所选索引的值从列表框分配给变量的正确方法是什么?用户选择列表框中的项目,然后输出会根据其选择而更改. 我用: variablename = listbox.text 在listBox_SelectedIndexChanged事件中,这是有效的. 当我使用button_click事件时,我使用: variablena
嗨,您好
将所选索引的值从列表框分配给变量的正确方法是什么?用户选择列表框中的项目,然后输出会根据其选择而更改. 我用: variablename = listbox.text 在listBox_SelectedIndexChanged事件中,这是有效的. 当我使用button_click事件时,我使用: variablename = listbox.selectedindex 但这在listbox_selectedindexchanged事件中不起作用. 如果可以像我上面那样使用它,或者如果我遇到问题以及为什么你不能使用selectedindex方法,请你告诉我. 谢谢! 解决方法
答:听起来你的变量是一个字符串,但你试图将SelectedIndex属性返回的值赋给它,这是一个整数.
B.如果您尝试检索与列表框的SelectedINdex关联的项的值,请使用索引返回对象本身(列表框是对象列表,通常但不总是,它们将成为字符串). Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object,ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged 'THIS retrieves the Object referenced by the SelectedIndex Property (Note that you can populate 'the list with types other than String,so it is not a guarantee that you will get a string 'return when using someone else's code!): SelectedName = ListBox1.Items(ListBox1.SelectedIndex).ToString MsgBox(SelectedName) End Sub 使用SelectedItem属性,这更直接一点: Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object,ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged 'This returns the SelectedItem more directly,by using the SelectedItem Property 'in the event handler for SelectedIndexChanged: SelectedName = ListBox1.SelectedItem.ToString MsgBox(SelectedName) End Sub (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |