ArGOO
ArGOO

Reputation: 23

C# Search item and return in Listview

I have some question about Listview in C# My listview contains with 2 column like this :

colDATA1          colDATA2
 Value1            Amount1
 Value2            Amount2
 Value3            Amount3
 Value4            Amount4

And what I am trying to make is search Amount5 in Listview If not exist then do something.And if exist then return the Value5

I am trying to search and use the code like this :

If (Listview1.items.containskey("Amount5"))
{}
else
{MessageBox.show("Not Found")}

or if exist then return the value5 *I have no idea how to do.

I am searching this in google but most of it have only 1 Column and when I use the code the code won't work.

My question is :
 1. How can I get Value5 if Amount5 exist.

Thank you.

The code to add the items

First Set listView1 Property "View : Details" Then Using this code
this.Listview1.Items.Add(new ListViewItem(new string[] { Value1, Amount1 }));

Upvotes: 0

Views: 1158

Answers (1)

Muhannad
Muhannad

Reputation: 455

The OP already figured it out but this is just for future reference in case someone needs it.

What OP was missing is that ListView holds its items as objects in the Items property.

If (Listview1.items.containskey("Amount5"))
{}
else
{MessageBox.show("Not Found")}

containsKey is usually in dictionaries-like data structures. However, a ListView controller's Items is ItemCollection (for dictionaries you can use a DataGrid)

In your case I would do this using Linq.

 // Returns the first item that satisfies the condition or null if none does.
        ListViewItem found = items.FirstOrDefault(i => i.SubItems[1].Text.Equals("Amount5"));

        if(found != null) {

            MessageBox.Show(found.SubItems[0].Text.ToString());
        }
        else {

            MessageBox.Show("Not Found!");

        }

You can still use a for loop to do the same thing too.

If I want to use a foreach loop (since Linq can't be directly used on ListView.Item)

      ListViewItem found = null;

        foreach (ListViewItem item in listView1.Items) {

            if (item.SubItems[1].Text.Equals("Amount5")) {

                // If a match was found break the loop.
                found = item;
                break;
            }

        }

        if (found != null) {

            MessageBox.Show(found.SubItems[0].Text.ToString());
        }
        else {

            MessageBox.Show("Not Found!");

        }

Hope this helps!

Upvotes: 1

Related Questions