Reputation: 3515
I have listview which is populated with list of data. Now I want to select desired row and on click button to recognize that item to delete from a collection.
Question is how to recognize selected row from the listview?
private void buttonDelete_Click(object sender, EventArgs e)
{
//selected data is of custom type MyData
var selected = (MyData)....?
}
Thanks
Upvotes: 3
Views: 1829
Reputation: 63387
I don't think you have to use casting for a deleting operation, just remove all the selected indices like this:
private void buttonDelete_Click(object sender, EventArgs e){
for (int i = listView1.SelectedIndices.Count - 1; i >= 0; i--)
listView1.Items.RemoveAt(listView1.SelectedIndices[i]);
}
or more simply:
private void buttonDelete_Click(object sender, EventArgs e){
foreach(ListViewItem item in listView1.SelectedItems)
listView1.Items.Remove(item);
}
As you can see the item which is selected is of type ListViewItem
, you can bind your data to this item via Text
property (if the data is string) or Tag
property. I don't understand what your CustomData
is, is it a type inheriting ListViewItem
?
Upvotes: 1
Reputation: 1243
Old School answer :) without any LINQ statements
if(yourListView.SelectedItems.Count > 0)
{
var item = yourListView.SelectedItems[0];
}
Upvotes: 1
Reputation: 32729
YOu should do this
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);
}
}
Upvotes: 0
Reputation: 6821
To add to @Zaphod's answer and make a little more robust:
private void buttonDelete_Click(object sender, EventArgs e)
{
if (yourListView.SelectedItems.Any())
{
//selected data is of custom type MyData
var selected = yourListView.SelectedItems.First();
}
}
You could use .Count > 0
instead of .Any()
and .SelectedItems[0]
instead of .First()
. Whatever you find more readable/maintainable.
Upvotes: 3
Reputation: 1438
This should works
private void buttonDelete_Click(object sender, EventArgs e)
{
//selected data is of custom type MyData
var selected = yourListView.SelectedItems.First();
}
Upvotes: 4