Home > Net >  How to retrieve SubItem.Text property from listview item
How to retrieve SubItem.Text property from listview item

Time:02-20

I am trying to retreieve ListView SubItem .Text property.

My ListView has two columns: ID and name. I want to access name for specific ID and store it in variable:

string nameValue = listView1.Items[0].SubItems[0].Text;

The above code should look at first item (index zero) at my listview and then get the first subitem's text. Sadly it takes the Item.Text instead of SubItem.Text so it stores "ID" column value instead of "Name" column value.

Where do I make the mistake? I have tried with different SubItems index values (getting obvious "OurOfRange exceptions or trying something like SubItems.Item[0] over SubItems[0] but it does not work either.

CodePudding user response:

Ah yes, I remember this catching me out the first time!

The SubItems array actually contains all the elements which includes in index [0] the Text.

So you simply need to increment the sub-index by 1 to get the value you expect. You should ideally also add a null check just to be sure and avoid exceptions.

string nameValue = listView1.Items[0].SubItems[1].Text;
  • Related