not-working .Contains in ListViewSubItem

Suriv

Active member
Joined
Jul 16, 2007
Messages
33
Programming Experience
1-3
OK, I have a strange problem with a ListView control.
The control has the property .View = Details, with 7 columns.

I want to determine whether or not a SubItem of an Item in a ListView exist or not with the following code:
VB.NET:
Expand Collapse Copy
Dim item As New ListViewItem
item.Text = strBlablabla

Dim subItem As New ListViewItem.ListViewSubItem(item, "blablablaSubItem")
If the SubItem really exists in the ListView, item.SubItems.Contains(subItem) should return True, right?
But it doesn't... why not?

Thx in advance :)
 
VB.NET:
Expand Collapse Copy
Dim item As New ListViewItem
item.Text = strSplit(0)

lvwNetworks.Items.Add(item)
item.SubItems.Add(strSplit(4))
item.SubItems.Add(strSplit(2))
item.SubItems.Add(strSplit(3))
item.SubItems.Add(strSplit(5))
item.SubItems.Add(strSplit(6))
item.SubItems.Add(strSplit(7))

Dim subItem As New ListViewItem.ListViewSubItem(item, strSplit(4))

If item.SubItems.Contains(subItem) Then
    MsgBox("Contains")
Else
    MsgBox("Does not contain")
End If
 
What happens if you do:

VB.NET:
Expand Collapse Copy
If item.SubItems.Contains([B]strSplit[/B](4)) Then
    MsgBox("Contains")
Else
    MsgBox("Does not contain")
End If
 
strSplit(4) is underlined with the error
Value of type 'String' cannot be converted to 'System.Windows.Forms.ListViewItem.ListViewSubItem'.
 
ah.. okay

Well, I guess it doesnt work because you make a new LVSubItem object that just so happens to be displaying the same string as an existing item, and then calling .Contains() which will use the default comparison.. Given that LVSubItem might never override .Equals() it will probably be using Object's .Equals() implementation, which is simply to compare the memory addresses. As you have 2 different objects, their memory addresses will be different.

Can I ask what youre using a listview for? Is it for tabular/grid representation of data? Would you think a grid would be better?
 
If think i've solved the problem without using a DataGridView:
VB.NET:
Expand Collapse Copy
if lvwNetworks.Items.Item(0).SubItems(1).Text = strSplit(4) then
msgbox("Contains")
else
msgbox("Does not contain")
end if

Thx anyway :)
 
Like many other collections, I believe .Contains() in context of a ListViewSubItemCollection uses the .SubItem.Name property to search; it does not look for the .SubItem.Text property. When you create your subitem, name it with a primary key and you will have better luck.
 
Back
Top