2013-05-15 117 views
1

我需要根据之前选择的内容在列表视图中动态选择一个项目。VB.NET:如何动态选择列表视图项目?

过去选择的项目从数据库中检索并添加到Arraylist中。这些项目需要从多个不同的列表视图中选择。

这样做索引像listRef1.Items(2).Checked = True没有问题,但我需要通过项目文本,即数组中的字符串之一。

到目前为止,我有这样的:

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() 
    If refid = 1 Then 
     listRef1.Items(refsArr(i)).Checked = True 
    ElseIf refid = 2 Then 
     listRef2.Items(refsArr(i)).Selected = True 
     listRef2.Select() 
    ElseIf refid = 3 Then 
     listRef3.Items.Item(refsArr(i)).Selected = True 
     listRef2.Select() 
    ElseIf refid = 4 Then 
     listRef4.Items.Item(refsArr(i)).Selected = True 
    End If 
Next 

有没有人有这个什么想法?谢谢。

回答

5

你需要遍历每个项目列表视图列表:

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 
1

你可以试试这个...

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 

和副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 
+0

通过迭代列表视图和阵列,并比较各做了两招,但是这是一个很好的解决方案。谢谢! – redned

0

的代码从listview控件动态地选择一个项目可以如下vb.net。

  • lvwomominiChair1是listview控件的名称。
  • 将其fullrowselect属性设置为true。

该代码将选择列表视图控件的第一列中的文本。

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 

可能存在,我们需要得到在ListView control.The下面的代码可用于purpose.It的行中的所有项目,假设有数据的五列在原始情况和是文本数据类型。这可以使用For..Next循环完成,如下所示。让0,1,2,3和4是五列索引。

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 
0

或者你也可以做到这一点,工作非常适合我:

ListView.Items(0).Selected = True 

ListView.Select() 
相关问题