2013-05-15 116 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() 
相關問題