Mr_Green
Mr_Green

Reputation: 41832

Compare a ListBox Item with ListView item based on indexes

I am new to c#. In my project I have two controls ListBox and ListView

ListBox --> lbxEmpName
ListView --> lvEmpDetails

I tried the below code:

     if (lvEmpDetails.Items.Count > 0)
       {
           for (int intCount = 0; intCount < lbxEmpName.Items.Count; intCount++)
           {
              for (int intSubCount = 0; intSubCount < lvEmpDetails.Items.Count; intSubCount++)
              {
                 if (lvEmpDetails.Items[intSubCount].Equals(lbxEmpName.Items[intCount]))
                 {
                    lbxEmpName.Items.Remove(lbxEmpName.Items[intCount]);
                 }
              }
           }
       }

If I run the above code, there are no matches between ListView Items and ListBox Items (Infact there must be some matches). When I debug my code, I saw the below thing: It is saying SelectedItem whereas I am giving here Items (Thats why my program is not matching items)
why it is showing SelectedItem = "" instead of Items ? Am I doing something wrong in my code? Please suggest.

enter image description here enter image description here

Upvotes: 0

Views: 632

Answers (2)

Mohammad Banisaeid
Mohammad Banisaeid

Reputation: 2626

ListView's Items contains objects of type ListViewItem. So there is no use in comparing those with objects in ListBox's Items.
If you want to compare their text, you must write something like this:

if (lvEmpDetails.Items[intSubCount].Text == (string)lbxEmpName.Items[intCount])
{
     // Do something here
}

Please note that a ListViewItem can have multiple sub-items and its Text property returns the first column of its data.

Upvotes: 2

Andrei dela Cruz
Andrei dela Cruz

Reputation: 628

Compare the string values that you want to compare not the object themselves.

Upvotes: 1

Related Questions