VB.NET: How to dynamically select a list view item?

与世无争的帅哥 提交于 2019-12-06 11:47:46

You'll need to loop through each item in the listview list:

For I as Integer = 0 to ListView.Items.Count - 1 Do
    If ListView.Items(i).Text = "Text" then
         ListView.Items(i).Selected = true
    End If
End For

You can try this ...

For i As Integer = 0 To refsArr.Count - 1
   'find the correct category id
    Dim cmdRefCat As New SqlCommand("SELECT RefID from ReferencesListTable WHERE            RefName = '" & refsArr(i) & "'", conn)
    Dim refid As Integer = cmdRefCat.ExecuteScalar()
    Select case refid
      case 1 
        CheckIt(refsArr(i),listRef1)
      case 2 
        CheckIt(refsArr(i),listRef2)
      case 3 
        CheckIt(refsArr(i),listRef3)
      case 4
        CheckIt(refsArr(i),listRef4)
    End Select
Next

And Sub CheckIt

Sub CheckIt(ByVal sRef as String, ByRef lvw as Listview)
    Dim x as Integer

    For x = 0 to lvw.Items.Count - 1 
        If lvw.Items(x).Text = sRef then
           lvw.Items(x).Selected = true
           exit for '-- if only 1 record   
        End If
    Next
End Sub

The code to select an item dynamically from the listview control can be as follows for vb.net.

  • Let lvwomominiChair1 is the name of the listview control.
  • Set its fullrowselect property as true.

The code will select the text in the first column of the listview control.

Private Sub  lvwomominiChair1_Click(sender As Object,e As EventArgs) Handles lvwomominiChair1.Click   
    Dim lvwitem as ListViewItem
    lvwitem = lvwomominiChair1.SelectedItems.Item(0)
    MsgBox("Selected item is  " + lvwitem.Text)
End Sub

There may be situations where we need to get all items in a row of a ListView control.The following code may be used for the purpose.It is assumed that there are five columns of data in a raw and are of the text data type.This can be done with a For..Next loop as follows.Let 0,1,2,3 and 4 are the five column indices.

Private Sub  lvwomominiChair1_Click(sender As Object,e As EventArgs) Handles lvwomominiChair1.Click   
        Dim i As Int32
        Dim str As String
        str =""
        For i =0 To 4
        str = str + " " + lvwomominiChair1.SelectedItems(0).SubItems(i).Text
        Next
        MsgBox("Selected items  of the five columns of the row are " +  str)
End Sub
Daniel

Or you can do this, works perfect for me:

ListView.Items(0).Selected = True

ListView.Select()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!