我有列表视图,其中填充了数据列表。现在我想选择所需的行并单击按钮以识别要从集合中删除的项目。
问题是如何从列表视图中识别选定的行?
private void buttonDelete_Click(object sender, EventArgs e)
{
//selected data is of custom type MyData
var selected = (MyData)....?
}
谢谢
这应该有效
private void buttonDelete_Click(object sender, EventArgs e)
{
//selected data is of custom type MyData
var selected = yourListView.SelectedItems.First();
}
要添加到@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()
。无论您发现什么更具可读性/可维护性。
老派回答:) 没有任何 LINQ 语句
if(yourListView.SelectedItems.Count > 0)
{
var item = yourListView.SelectedItems[0];
}
我认为您不必使用强制转换进行删除操作,只需删除所有选定的索引,如下所示:
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
吗?
你应该做这个
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);
}
}