将 ListView 中的元素存储到列表中

Store elements from a ListView into a List

因为我没有找到任何有用的东西,所以我在这里问我的问题:

我有一个 ListView,其中我通过单击 select 整行。现在我想将这些 selected 项目存储到一个列表中,但不知道它应该如何工作。

       List<String> itemSelected = new List<String>();

        foreach (var selectedRow in listView1.SelectedItems)
        {
            itemSelected.Add(selectedRow);
        }

这不起作用,因为我需要一个索引 (selectedRow[?]) 或类似的东西。单击行时如何存储第一列的值?

编辑:问题是 ListViewItems 的类型为 "object"

ListView 以这种方式填充:

 using (SqlConnection connection = new SqlConnection(connectionQuery))
            {
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    col1 = row.Cells[col1.Text].Value.ToString();
                    col2 = row.Cells[col2.Text].Value.ToString();

                    col1Cells.Add(col1);
                    col2Cells.Add(col2);
                }

            }

将 ListView 绑定到非平凡类型的列表是很常见的。

然后你可以处理 SelectedItemChanged 或类似的东西。您收到整个对象(类型 object),您可以将其转换为您的自定义类型并检索您想要的任何属性

您可以这样做:

ListViewItem listViewItem = this.listView1.SelectedItems.Cast<ListViewItem>().FirstOrDefault();
if (listViewItem != null)
{
    string firstColumn = listViewItem.Text;
    string secondColumn = listViewItem.SubItems[0].Text;
    // and so on with the SubItems
}

如果您有更多选择项并且只需要第一列的值,您可以使用:

List<string> values = listView1.SelectedItems.Cast<ListViewItem>().Select(listViewItem => listViewItem.Text).ToList();