列表框中的值到vb.net中的列表变量

时间:2013-10-17 15:46:37

标签: vb.net

我正在使用vb.net 我有一个列表框名称LSTlocations..i可以从该列表框中选择多个位置..我正在获取特定位置的ID到一个列表varibale ..所以我给出了这样的代码:

 cnt = LSTlocations.SelectedItems.Count

    Dim strname As String
    If cnt > 0 Then
        For i = 0 To cnt - 1
            Dim locationanme As String = LSTlocations.SelectedItems(i).ToString
            Dim locid As Integer = RecordID("Locid", "Location_tbl", "LocName", locationanme)
            Dim list As New List(Of Integer)
            list.Add(locid)

        Next 
    End If

但我没有在我的列表varibale中获取我所有被选中的位置ID。我可以从列表框中获取所有选定的位置ID以列出varable

1 个答案:

答案 0 :(得分:1)

在循环所选项目时,您初始化应存储ID的整数 在每个循环中,列表都是新的并且为空,然后添加新的locid,但是在后续循环中将其松开。

所以你最终只得到列表中的最后一个整数

简单地说,在循环外移动列表的声明和初始化

Dim strname As String
Dim list As New List(Of Integer)

cnt = LSTlocations.SelectedItems.Count
For i = 0 To cnt - 1
    Dim locationanme As String = LSTlocations.SelectedItems(i).ToString
    ' for debug
    ' MessageBox.Show("Counter=" & i & " value=" & locationanme)
    Dim locid As Integer = RecordID("Locid", "Location_tbl", "LocName", locationanme)
    ' for debug
    ' MessageBox.Show("ID=" & locid)
    list.Add(locid)
Next 
Console.WriteLine(list.Count)

For Each num in list
    MessageBox.Show("LocID:" & num)