我有一个由10个名字组成的CheckedListBox A到J(这是一个字符串,但这里我只是使用abc),我想做它,这样每次用户检查某个东西时,文本都会同时显示在列表框中。我试过这样做:
For i = 0 To chklistbxDrugAvailableList.Items.Count - 1
Dim drugs As String = CType(chklistbxDrugAvailableList.Items(i), String)
If chklistbxDrugAvailableList.GetItemChecked(i) Then
listbxYourOrder.Items.Add(drugs)
End If
'drugs = nothing
Next
但是,当我检查A、B、C时,列表框中的文本被重复如下:
A
A
B
A
B
C
我不知道为什么会这样。我没有将drugs
声明为数组。即使我使用drugs = nothing
,它仍然会给出重复的值。
我该怎么办?抱歉,如果这是个问题。
发布于 2020-11-18 14:49:00
以下是我要做的事情:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
'Clear the current ListBox contents.
ListBox1.Items.Clear()
'Get the indexes of the currently checked items.
Dim checkedIndices = CheckedListBox1.CheckedIndices.Cast(Of Integer)()
'Add the current index to the list if the item is being checked, otherwise remove it.
checkedIndices = If(e.NewValue = CheckState.Checked,
checkedIndices.Append(e.Index),
checkedIndices.Except({e.Index}))
'Get the checked items in order and add them to the ListBox.
ListBox1.Items.AddRange(checkedIndices.OrderBy(Function(n) n).
Select(Function(i) CheckedListBox1.Items(i)).
ToArray())
End Sub
或者像这样:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
'Get the indexes of the currently checked items.
Dim checkedIndices = CheckedListBox1.CheckedIndices.Cast(Of Integer)()
'Add the current index to the list if the item is being checked, otherwise remove it.
checkedIndices = If(e.NewValue = CheckState.Checked,
checkedIndices.Append(e.Index),
checkedIndices.Except({e.Index}))
'Get the checked items in order and add them to the ListBox.
ListBox1.DataSource = checkedIndices.OrderBy(Function(n) n).
Select(Function(i) CheckedListBox1.Items(i)).
ToArray()
End Sub
区别在于,由于第二个选项使用数据绑定,默认情况下将选择ListBox
中的第一个项。
需要有点冗长的原因是,ItemCheck
事件是在选中或未选中项之前引发的。因此,我们需要先获得当前选中的项,然后添加或删除当前项,这取决于当前项是选中还是未选中。
编辑:
这里有一个不需要清除ListBox
的选项
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Dim item = CheckedListBox1.Items(e.Index)
If e.NewValue = CheckState.Checked Then
ListBox1.Items.Add(item)
Else
ListBox1.Items.Remove(item)
End If
End Sub
这样做的问题是,项目将以检查它们的顺序出现在ListBox
中,而不是它们在CheckedListBox
中的出现顺序。其他选项将两个列表中的项目保持相同的顺序。
发布于 2020-11-18 18:36:08
如果我理解你的问题,我会这样做:
lstbxYourOrder.Items.Clear()
For Each l As String In chklistbxDrugAvailableList.CheckedItems
listbxYourOrder.Items.Add(l)
Next
https://stackoverflow.com/questions/64894864
复制相似问题