Search code examples
c#winformslistviewselected

set selected item of listview according to a value


C# winforms. I have a listview, and for each item clicked I show its properties in labels and textboxes. They are not binded in any way, I do manually. So I change values in textboxes (via next and previous record buttons) and the listview.selected doesn't change.

I've done this my way, but I think maybe there's some optimization or even a single method to do this. I'm seeking something like selected=itemwithkey(idTextBox)

for (int i = 0; i < lstvClientes.Items.Count; i++) {
   if (lstvClientes.Items[i].SubItems[0].Text == idTextBox.Text) {
      lstvClientes.Items[i].Selected = true; break;
   }
}

Suggestions? thank you community.


Solution

  • You can use ListView.FindItemWithText method:

    var item = lstvClientes.FindItemWithText(idTextBox.Text);
    if (item != null)
        item.Selected = true;