user3379482
user3379482

Reputation: 567

How to get the index of a listview item by its text

I'm trying to get the index of an item by its text in a listview.

For example, I have a list view which contains items: "item1", "item2", etc.

I've tried to get the index of "item2" like this:

MessageBox.Show(listView1.Items.IndexOf("item2");

But it's not working:

can't convert from int to string / can't convert from string to System.windows.forms.listviewItem

How can I fix it?

Upvotes: 4

Views: 27776

Answers (2)

Christos
Christos

Reputation: 53958

Let us have a ListView, whose ID is listView1. In order we get the items that are in this list view, we have to use the following code:

listView1.Items

What's the type of listView1.Items?

The type of listView1.Items is ListViewItemCollection.

For more documentation on this, please have a look here.

What's the type of the objects that are stored in this collection, listView1.Items?

The type of the objects that are stored in listView1.Items is ListViewItem.

For more documentation about this class, please have a look here.

Why doesn't MessageBox.Show(listView1.Items.IndexOf("item2"); work*?

The reason why you get the error you posted on your comment is that method called IndexOf takes as a parameter an object of type ListViewItem, and you pass an object of type string as a parameter to this method.

Actually, as you can see here, the signature of the method called IndexOf is the following one:

 public int IndexOf(
    ListViewItem item
)

So in order you get the index of the item you want, you have to pass to the method called IndexOf a ListViewItem. For this reason I suggest you try the following code:

// Select the first ListViewItem of items, whose Text is item2
ListViewItem item = listView1.Items
                             .Cast<ListViewItem>()
                             .FirstOrDefault(x=>x.Text=="item2");

MessageBox.Show(listView1.Items.IndexOf(item).ToString());

Upvotes: 3

Alex Skiba
Alex Skiba

Reputation: 437

The ListView.FindItemWithText method does what you want:

var item = listView1.FindItemWithText("item2");

if (item != null)
{
    MessageBox.Show(listView1.Items.IndexOf(item).ToString());
}

Upvotes: 9

Related Questions