如何从 vb.net 的列表框中获取选定的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19562945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:15:32  来源:igfitidea点击:

How to get selected items from listbox from vb.net

vb.netlistbox

提问by bhu

I'm using ListBoxto display some value, it works properly but when I am trying to get the selected item from the list box it shows an error null reference error.

ListBox用来显示一些值,它工作正常,但是当我尝试从列表框中获取所选项目时,它显示错误空引用错误。

Below is my code that I have written to get values from ListBox:

下面是我为从 ListBox 获取值而编写的代码:

 For i As Integer = 0 To lsttasks.SelectedItems.Count - 1
    userTaskDtlSrNo = Val(lsttasks.SelectedItems(i).ToString())
    If userTaskDtlSrNos <> "" Then userTaskDtlSrNos &= ","
    userTaskDtlSrNos &= userTaskDtlSrNo
 Next

Can anyone tell me what's wrong with this code?

谁能告诉我这段代码有什么问题?

回答by Leon

You don't need the Val()function there

你不需要Val()那里的功能

Don't forget to declare Dim userTaskDtlSrNo as String

别忘了申报 Dim userTaskDtlSrNo as String

Use: userTaskDtlSrNo = lsttasks.SelectedItems(i).ToString()

用: userTaskDtlSrNo = lsttasks.SelectedItems(i).ToString()

回答by 0000

I believe your assigning a string to a integer, declare userTaskDtlSrNo as String, then use

我相信您将字符串分配给整数,将 userTaskDtlSrNo 声明为字符串,然后使用

userTaskDtlSrNo = Val(lsttasks.SelectedItems(i).ToString())

if you need to change userTaskDtlSNo to an integer after then just use

如果您需要在之后将 userTaskDtlSNo 更改为整数,则只需使用

Dim intUserTask As Integer
Integer.TryParse(userTaskDtlSrNo, intUserTask)

to assign a new variable with same value as an integer, i dont know the rest of your code but i see no reason why this would not solve your problem. :-)

分配一个与整数相同值的新变量,我不知道你的其余代码,但我看不出为什么这不能解决你的问题。:-)

回答by Agentleader1

This can be way easier than it looks.

这可能比看起来容易得多。

If you want to delete an object that is selected:

如果要删除选定的对象:

'let recips be the listbox name
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Recips.Items.Remove(Recips.SelectedItem)
End Sub

If you want to get the selected item (like for setting it to a string):

如果要获取所选项目(例如将其设置为字符串):

'let pie be a string variable, and recips to be the listbox again respectively
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
pie = Recips.selectedItem
End Sub

I hope this was enough for you, I'm not sure if I covered on enough information. Please comment so, if I forgot. Accept this answer if this helped.

我希望这对你来说已经足够了,我不确定我是否涵盖了足够的信息。请评论,如果我忘记了。如果这有帮助,请接受此答案。