开发者

Get ListView items that are checked

开发者 https://www.devze.com 2023-02-02 09:22 出处:网络
I have listview with combox=true containg images. Eac开发者_如何学JAVAh item is assigned a tag.

I have listview with combox=true containg images. Eac开发者_如何学JAVAh item is assigned a tag. I can get tag of focussed item:

string name = this.lstview1.FocusedItem.Tag.ToString();

I can get index of checked item:

  list = lstview1.CheckedIndices.Cast<int>().ToList();

How do I get the tag of the checked item?


You can use CheckedItems property instead of CheckedIndices:

var selectedTags = this.listView1.CheckedItems
                                 .Cast<ListViewItem>()
                                 .Select(x => x.Tag);

Anyway, also CheckedIndices can be used, e.g.:

var selectedTags = this.listView1.CheckedIndices
                                 .Cast<int>()
                                 .Select(i => this.listView1.Items[i].Tag);

EDIT:

Little explanation of LINQ Select():

The following code:

var selectedTags = this.listView1.CheckedItems
                                 .Cast<ListViewItem>()
                                 .Select(x => x.Tag);
foreach(var tag in selectedTags)
{
   // do some operation using tag
}

is functionally equal to:

foreach(ListViewItem item in this.listView1.CheckedItems)
{
   var tag = item.Tag;
   // do some operation using tag
}

In this particular example is not so useful, nor shorter in term of code length, but, believe me, in many situations LINQ is really really helpful.


How about


var x = listView1.Items[listView1.CheckedIndices.Cast().ToList().First()].Tag;

?

0

精彩评论

暂无评论...
验证码 换一张
取 消