1

i am using vb.net i have a list box name LSTlocations..i can select multiple locations from that list box..i am fetching id of particular location to one list varibale..so i given code like this:

 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

but i am not getting my all seclected locations id in my list varibale..how i can get all selected locations id from my listbox to list varable

1 Answer 1

1

While looping on the selected items you initialize the of integers that should store the ids.
At every loop the list is new and empty, then you add the new locid but you loose it at the subsequent loop.

So you end up with only the last integer in the list

Simply, move the declaration and initialization of the list outside the loop

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Difficult to say. What is the value of cnt when you start the loop? You could try to add a MessageBox showing the value of LSTlocation.SelectedItems(i) and the value of locid
first time it self i want to show all selected Id...separated by comma,,how i can do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.