ListViewItemCollection Contains Method

  • Thread starter Thread starter Giggsy
  • Start date Start date
G

Giggsy

Hello,

I am creating an application where I have to list my found bluetooth
devices in a ListView. So after each search I will check if the device
already exists.
I do that with the following code, but it doesn't work. It can't be to
difficult I think, but I still haven't solve it..so I ask for your
help!

Can please someone tell me what I do wrong?

foreach (BluetoothDeviceInfo btdi in bdi)
{
ListViewItem lviDevice = new ListViewItem(btdi.DeviceID.ToString());
lviDevice.SubItems.Add(btdi.DeviceName);

if (!lstBTDevices.Items.Contains(lviDevice))
{
lstBTDevices.Items.Add(lviDevice);
bListChanged = true;
}
}

Best regards,

Giggsy
 
Can please someone tell me what I do wrong?

See inline comments...
foreach (BluetoothDeviceInfo btdi in bdi)
{
ListViewItem lviDevice = new ListViewItem(btdi.DeviceID.ToString());

^^ In this line, you are creating a *new* ListViewItem.
lviDevice.SubItems.Add(btdi.DeviceName);

if (!lstBTDevices.Items.Contains(lviDevice))

^^ In this line, you are checking whether the new ListViewItem that
you just created is *the same object* as an existing ListViewItem that
you previously created. This is impossible, so the test always fails.
{
lstBTDevices.Items.Add(lviDevice);
bListChanged = true;
}
}

You'll have to manually search all your list view items for a Text
property that equals the one of your new ListViewItem:

bool found = false;
foreach (ListViewItem item in lstBTDevices.Items)
if (item.Text == lviDevice.Text) {
found = true;
break;
}

if (!found) {
lstBTDevices.Items.Add(lviDevice);
bListChanged = true;
}

What you did would work if ListViewItem was a value type (e.g. an
integer number), but it's a reference type so it doesn't work. Two
different reference type objects are always different objects, even if
they contain the same values, except if you override Object.Equals.

This stuff is a bit tricky but essential for .NET programming. You'll
find more details in Jeff Richter's standard book "Applied Microsoft
..NET Framework Programming", Microsoft Press.
 
Hello Christoph Nahr,

Thank you for your quick reply. It works now.
I also understand what I did wrong, it make sense now.

Thanks again

Giggsy
 
Back
Top