简体   繁体   English

Selected Listbox Items - 将数据添加到数组 VB.net

[英]Selected Listbox Items - to add data to array VB.net

Struggling to test which Listbox items are selected.努力测试选择了哪些列表框项目。 I want to allow the user to select multiple items in a listbox so that a string can be stored in an array where the list is also stored.我希望允许用户在列表框中选择多个项目,以便可以将字符串存储在也存储列表的数组中。 It is a rollcall system (a task for my Year 10 students).这是一个点名系统(我 10 年级学生的任务)。 I just can't get the syntax right for the listbox.我只是无法获得适合列表框的语法。 The Listbox is set to MultiSelection.列表框设置为多选。

BTW顺便提一句

If Listbox.SelectedItem = true Then

Does not work.不起作用。 It returns an error.它返回一个错误。

My code below returns the first selected item (in a message box)- but not the others.我下面的代码返回第一个选定的项目(在消息框中) - 但不返回其他项目。 I'm just going round and round now.我现在只是四处走动。 there must be an easier way.必须有更简单的方法。 Thoughts?想法?

Private Sub BtnRollCall1_Click(sender As Object, e As EventArgs) Handles btnRollCall1.Click
    Dim ExcursionArray(29, 4) As String
    Dim selected As Integer
    Dim LoadNames As StreamReader = File.OpenText("ClassList.txt")
    For i = 0 To 29
        ExcursionArray(i, 0) = (LoadNames.ReadLine())
        lbxRollCall.Items.Add(ExcursionArray(i, 0))
    Next

    For Each SelectedItem As string In lbxRollCall.SelectedItems
        selected = lbxRollCall.SelectedIndex
        ExcursionArray(selected, 1) = "a"
    Next

    For x = 0 To 29
        If (ExcursionArray(x, 1) = "a") Then
            MsgBox(ExcursionArray(x, 0))
        End If

    Next
End Sub

It appears that what you actually want to do is update a 2D array and set the second 'column' to "a" if the corresponding 'row' is selected in the ListBox .如果在ListBox选择了相应的“行”,那么您实际上想要做的是更新一个二维数组并将第二个“列”设置为“a”。 One way to do that would be like so:一种方法是这样的:

For Each selectedIndex In lbxRollCall.SelectedIndices
    ExcursionArray(selectedIndex, 1) = "a"
Next

Another option would be like so:另一种选择是这样的:

For i = 0 To ExcursionArray.GetUpperBound(0)
    If lbxRollCall.GetSelected(i) Then
        ExcursionArray(i, 1) = "a"
    End If
Next

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM