开发者

Get ListView items that are checked

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜