A couple things to know about the quirky ListView control (examples in C#):
Upon adding an Item to the ListView, that Item mysteriously also gets a new SubItem. So an Item will never have SubItem.Count == 0. In your case, Item.SubItem[0] will be in the column Columns[0] (with ColumnHeader ID, I believe you said). Item.SubItem[1] will be under Columns[1] (with ColumnHeader FirstName), etc.
Secondly, ListViews have two relevant collections: Items and Columns. Items is a collection of ListViewItems while Columns is a collection of ColumnHeaders. ListViews also have a collection called SelectedItems, a subset of Items (so it, too, holds ListViewItems). Each instantiated ListViewItem will have its own SubItems collection (whose first item, as we said, actually takes the text of the item itself), which is a collection of ListViewSubItems. The catch: ListViewSubItem is a sub-class of ListViewItem, which makes it illegal to write:
ListViewSubItem lvsi = ...;
You must instead write:
ListViewItem.ListViewSubItem lvsi = ...;
Ok, so back to your question. Let's call your ListView listView1. Assuming that ID is your first ColumnHeader (ie, listView1.Columns[0]), you can get all of the selected IDs with the following code:
foreach (ListViewItem lvi in listView1.SelectedItems) { MessageBox.Show(lvi.ToString()); // or just access the ID with lvi.Text }
However, this only works because ID is the first column. If ID is the second column (Columns[1]), you will have to do something like this:
foreach (ListViewItem lvi in listView1.SelectedItems) { ListViewItem.ListViewSubItem lvsi = lvi.SubItems[1]; // extra step for clarity MessageBox.Show(lvsi.ToString()); }
To make your code even more general, first find the index of the column with header "ID" like this:
int index; foreach (ColumnHeader colhead in listView1.Columns) { if(colHead.Text == "ID") index = colHead.Index; }
Tom
|