Searching for text in a listview control

bjwade62

Centurion
Joined
Oct 31, 2003
Messages
104
I have two listviews. lvwA and lvwB. I'd like to search lvwB for the existence of the same item in lvwA. I'm not sure how to go about it.

Any help? Thanks.
 
Initially I was going to say you could use the Contains method of the Items collection however upon a quick test that didn't seem to work. One way of doing it would be something like this...
C#:
		private void cmdSearch_Click(object sender, System.EventArgs e)
		{
			if(lvwA.SelectedItems.Count!=0)
			{
				string searchText = lvwA.SelectedItems[0].Text;
				bool found = FindItem(searchText);
			}
		}

		private bool FindItem(string searchText)
		{
			for(int i = 0; i < lvwB.Items.Count; i++)
			{
				if(lvwB.Items[i].Text == searchText)
				{
					return true;
				}
			}
			
			return false;
		}
 
Sorry. I should have been more specific. I'm using VB in VS2005.

Cags said:
Initially I was going to say you could use the Contains method of the Items collection however upon a quick test that didn't seem to work. One way of doing it would be something like this...
C#:
		private void cmdSearch_Click(object sender, System.EventArgs e)
		{
			if(lvwA.SelectedItems.Count!=0)
			{
				string searchText = lvwA.SelectedItems[0].Text;
				bool found = FindItem(searchText);
			}
		}

		private bool FindItem(string searchText)
		{
			for(int i = 0; i < lvwB.Items.Count; i++)
			{
				if(lvwB.Items[i].Text == searchText)
				{
					return true;
				}
			}
			
			return false;
		}
 
Visual Basic:
Private Function FindItems(ByVal searchText As String) As Boolean
        For i As Single = 0 To i < lvwB.Items.Count
            If (lvwB.Items(i).Text = searchText) Then
                Return True
            End If
        Next
        Return False
    End Function

    Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If (lvwA.SelectedItems.Count <> 0) Then
            Dim searchText As String = lvwA.SelectedItems(0).Text
            Dim found As Boolean = FindItems(searchText)
        End If
    End Sub
 
Wow. Excellent. Thank you so much. Works great. Now I'll have to break it down to learn from what you did. Thanks again!

Cags said:
Visual Basic:
Private Function FindItems(ByVal searchText As String) As Boolean
        For i As Single = 0 To i < lvwB.Items.Count
            If (lvwB.Items(i).Text = searchText) Then
                Return True
            End If
        Next
        Return False
    End Function

    Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If (lvwA.SelectedItems.Count <> 0) Then
            Dim searchText As String = lvwA.SelectedItems(0).Text
            Dim found As Boolean = FindItems(searchText)
        End If
    End Sub
 
Back
Top