Search code examples
c#listviewsubitem

How to add Tag and subitem in listview c#


I want to display tag and subitem in my listview , those items come by using while statement. here the code

int id = 0;
                    while ((line = sr.ReadLine()) != null)
                    {
                        id++;
                        string[] columns = line.Split(',');
                        ListViewItem item = new ListViewItem();
                        item.Tag = id;
                        item.SubItems.Add(columns[1]);
                        lv_Transactions.Items.Add(item);
                    }

subitems cab be displayed but the tag just appear blanks. Someone know to fix this please help me


Solution

  • The Tag property is not displayable. You will need to add the contents of the tag as a subitem or otherwise embed it in the data you are showing to the user.

    You have three choices on how to implement this:

    1) ListViewItem item = new ListViewItem(id.ToString());

    2) item.Text = id.ToString(); (this is effectively the same as 1)

    3) item.SubItems(id.ToString()); if you want the id to appear in the list of subitems.

    Update

    SubItems will only work correctly if you have defined Columns in the ListView and have set the ListView's View to View.Details.

    Assuming that you have not done this, the following line:

    item.SubItems.Add(columns[1]);
    

    should be modified to be:

    item.Text = columns[1];