3

我有列表视图,其中填充了数据列表。现在我想选择所需的行并单击按钮以识别要从集合中删除的项目。

问题是如何从列表视图中识别选定的行?

private void buttonDelete_Click(object sender, EventArgs e)
{
    //selected data is of custom type MyData
    var selected = (MyData)....?
}

谢谢

4

5 回答 5

4

这应该有效

  private void buttonDelete_Click(object sender, EventArgs e)
    {
        //selected data is of custom type MyData
        var selected = yourListView.SelectedItems.First();
    }
于 2013-07-17T07:56:40.457 回答
3

要添加到@Zaphod 的答案并使其更加健壮:

private void buttonDelete_Click(object sender, EventArgs e)
{
    if (yourListView.SelectedItems.Any())
    {
         //selected data is of custom type MyData
         var selected = yourListView.SelectedItems.First();
    }
}

您可以使用.Count > 0代替.Any().SelectedItems[0]代替.First()。无论您发现什么更具可读性/可维护性。

于 2013-07-17T07:58:38.970 回答
1

老派回答:) 没有任何 LINQ 语句

if(yourListView.SelectedItems.Count > 0)
{
  var item = yourListView.SelectedItems[0];
}
于 2013-07-17T08:06:32.077 回答
1

我认为您不必使用强制转换进行删除操作,只需删除所有选定的索引,如下所示:

private void buttonDelete_Click(object sender, EventArgs e){
    for (int i = listView1.SelectedIndices.Count - 1; i >= 0; i--)                
         listView1.Items.RemoveAt(listView1.SelectedIndices[i]);
}

或更简单地说:

private void buttonDelete_Click(object sender, EventArgs e){
    foreach(ListViewItem item in listView1.SelectedItems)                
         listView1.Items.Remove(item);
}

如您所见,选择的项目是 type ListViewItem,您可以通过Text属性(如果数据是字符串)或Tag属性将数据绑定到该项目。我不明白你CustomData是什么,它是一种类型继承ListViewItem吗?

于 2013-07-17T08:21:10.660 回答
0

你应该做这个

  private void buttonDelete_Click(object sender, EventArgs e)
  {        

    if (yourListView.SelectedItems.Any())
   {
     //selected data is of custom type MyData
     var selected = (MyData)yourListView.SelectedItems[0];
    YourCollection.Remove(selected);
   }
  }
于 2013-07-17T08:02:47.583 回答