Search code examples
c#.netwinformslistviewsubitem

Get SubItem value when double-clicking on Item in ListView


I have a listview with 2 columns, and when the I double click on an item, i need to display the value of its corresponding sub item in a TextBox control. How can I do this?

I searched Google, but it didn't return anything helpful, probably because I'm not exactly sure what to search for.

Thank you


Solution

  • The MSDN links you'll want to read are ListViewItem and ListViewSubItem.
    You access the subitems of your list view item through the ListViewItem.SubItems property Most important thing to remember is that the first sub-item refers to the owner list view item so to access the actual sub-items you need to index starting at 1. This will return you a ListViewSubItem object and you can get it's text string by calling ListViewSubItem.Text.

    i.e
    SubItems[0] gives you the 'parent' list view item
    SubItems[1] gives you the first sub-item etc

    Quick, nasty code snippet

    private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {
          ListView.SelectedIndexCollection sel = listView1.SelectedIndices;
    
          if (sel.Count == 1)
          {
              ListViewItem selItem = listView1.Items[sel[0]];
              textBox1.Text = selItem.SubItems[1].Text;
          }
    }
    

    Hope that helps