Remove the Selected Item From ListView - c#

How can I remove a selected item from a listview?

foreach ( ListViewItem eachItem in listView1.SelectedItems)
{
listView1.Items.Remove(eachItem);
}
where listView1 is the id of your listview.

When there is just one item (Multiselect = false):
listview1.SelectedItems[0].Remove();
For more than one item (Multiselect = true):
foreach (ListViewItem eachItem in listView1.SelectedItems)
{
listView1.Items.Remove(eachItem);
}

listBox.Items.RemoveAt(listBox.SelectedIndex);

Well, although it's a lot late, I crossed that problem recently, so someone might cross with this problem again. Actually, I needed to remove all the selected items, but none of the codes above worked for me. It always throws an error, as the collection changes during the foreach. My solution was like this:
while (listView1.SelectedIndex > 0)
{
listView1.Items.RemoveAt(listView1.SelectedIndex);
}
It won't throw the error as you get position of the last selected item (Currently), so even after you remove it, you'll get where it is now. When there is no items selected anymore, the SelectedIndex returns -1 and ends the loop. This way, you can make sure that there is no selected item anymore, nor that the code will try to remove an item in a negative index.

listView1.Items.Cast<ListViewItem>().Where(T => T.Selected)
.Select(T => T.Index).ToList().ForEach(T => listView1.Items.RemoveAt(T))

Yet another way to remove item(s) from a ListView control (that has GridView) (in WPF)--
var selected = myList.SelectedItems.Cast<Object>().ToArray();
foreach(var item in selected)
{
myList.Items.Remove(item);
}
where myList is the name of your ListView control

foreach (DataGridViewRow dgr in dgvComments.SelectedRows)
dgvComments.Rows.Remove(dgr);

Related

Loop doesn't iterate through listview

Could someone help me with this problem I am having? I am trying to search through a listview for occurrences of a string inputted via a textbox and record the location index value. Now although the code could be improved... it works. The problem I am having is the loop doesn't iterate. The code only displays the first index value even if there are more than one occurrences.
Could someone show me how to get this loop to loop?
Thanks in advance...
foreach (ListViewItem item in listView1.Items){
foreach (ListViewItem.ListViewSubItem subItem in item.SubItems){
if (subItem.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
var index = listView1.FindItemWithText(textBox1.Text.ToLower());
MessageBox.Show(listView1.Items.IndexOf(index).ToString());
count++;
}
}
}
You need to change this
var index = listView1.FindItemWithText(textBox1.Text.ToLower());
MessageBox.Show(listView1.Items.IndexOf(index).ToString())
to this
var index = item.Index;
MessageBox.Show(listView1.Items[index].ToString())
#johnny-mopp is correct that the finditemwithtext will only return one item, therefore it makes the loop completely redundant if you only wanted the first item.
Maybe something like this will work?
var index = listView1.Select(x=>x.IndexOf(textBox1.Text.ToLower(), StringComparison.Ordinal));

c# select listview item if two listviews contains it

In my program I have 2 listviews and 1 button.
When I press the button, every listview item in the first listview will be selected in the second listview. The items in the first listview always exist in the second listview, but not the other way around.
I'm having trouble with selecting the items in the second listview. I'm trying to get the index with IndexOf.
foreach (ListViewItem item in firstListView.Items)
{
int index = secondListView.Items.IndexOf(item);
secondListView.Items[index].Selected = true;
}
I always get an error that index is -1 when I click the button. And I don't understand what I'm doing wrong.
SOLUTION
So what I tried to do here finding an index of an item which belongs to a different listview, and it doesn't work like that. Even though the text in both listviews are the same, the listview items are not identically the same because they are reference types.
I was not able to use the Text property because items could have the same text. So the solution I had was putting an unique integer in the Tag property for each ListViewItem. Since integers are value types, I can use that integer to check whether the ListViewItem in the first listview is in the second.
// Loop through each item in the first listview
foreach (ListViewItem item1 in firstListView.Items)
{
// For each item in the first listview, loop through the second listview to find if it's there
foreach (ListViewItem item2 in secondListView.Items)
{
// Check if item1 is identical to item2 by looking at its tag
if (int.Parse(item1.Tag) == int.Parse(item2.Tag))
{
// The item has been found and will be selected!
item2.Selected = true;
}
}
}
You can use such linq query to select items of the second list which exist in the first list too:
var items = from i1 in listView1.Items.Cast<ListViewItem>()
from i2 in listView2.Items.Cast<ListViewItem>()
where i1.SubItems.Cast<ListViewItem.ListViewSubItem>()
.Where((s, i) => s.Text != i2.SubItems[i].Text).Count() == 0
select i2;
items.ToList().ForEach(x => { x.Selected = true; });
Note:
When to try to use secondListView.Items.IndexOf method to find an item which belongs to the firstListView you can not expect it to find the item. The item you are trying to find its index, doesn't exists in second listview's item collection. You should find items using Text property of the item and sub items.
Well the same item obviously cant exist in two different lists.
If the text is the same, then try looking by it:
foreach (ListViewItem listViewItem in l1.Items)
{
var item = l2.Items.Cast<ListViewItem>().Where(lvi => lvi.Text == listViewItem.Text);
item.Selected=true;
}
Or:
foreach (ListViewItem listViewItem in l2.Items.Cast<ListViewItem>()
.Where(lvi => l1.Items.Cast<ListViewItem>().Any(lvi2 => lvi.Text == lvi2.Text))
{
listVieItem.Selected=true;
}
IndexOf returns -1 if it cannot find the object passed to it in the list. My guess is that you have an issue with your equality comparison. Do the objects in the lists implement IComparable? Otherwise they may not be finding the items correctly and are reverting to a bad equality comparison. ListViewItem may not be comparing how you expect.
you can try finding the item by text and then get the index like this
foreach (ListViewItem item in firstListView.Items)
{
var itm = secondListView.FindItemWithText(item.Text);
int index = secondListView.Items.IndexOf(itm);
secondListView.Items[index].Selected = true;
secondListView.Select();
}
what FindItemWithText will do is get the item in secondListView which will be of same name as in firstListView and IndexOf will get the index of item in secondListView
Edit
This solution is good when you have two lists whose items are same and does not include any repetition in name else if you have two items in secondListView with same name FindItemWithText will get the first item only.

c# loop listbox selected items

I have a listbox on a form set to allow multiple selections. I want to loop through each selected item, store the selected value in a variable and do some work. I've tried many different variations of code to do this, but so far nothing has worked. Any help would be greatly appreciated! My code is below:
foreach (var item in systemList.Items)
{
string systemName = systemList.SelectedItems.ToString();
//do some work//
}
You can get all SelectedItems using below code:
var items = systemList.Items.Cast<ListItem>().Where(item => item.Selected);
You can then loop through the items
foreach (var item in items)
{
//Access value of each item by calling item.Value
}
foreach (var item in systemList.SelectedItems)
{
string systemName = item.ToString();
//do some work//
}
make sure listbox Selection mode is set to other than single!

How to remove all items except the first item from dropdownlist in C#?

I need to clear drpAddressTypes dropdown values except the first item and bind again that dropdownlist.
drpAddressTypes.Items.Clear();
var lstAddressTypes = repository.GetAddressTypes(userId);
if (lstAddressTypes != null)
{
foreach (var item in lstAddressTypes)
{
var addressType = new ListItem(item, item);
drpAddressType.Items.Add(addressType);
}
}
When I am using drpAddressTypes.Items.Clear(); it is clearing all items.
How can I clear all items except the first item.
Thanks in advance. :)
You could retrive the firstitem and then clear the list and add the item again.
var firstitem = drpAddressType.Items[0];
drpAddressType.Items.Clear();
drpAddressType.Items.Add(firstitem);
Use Items.RemoveRange(1, items.Count-1)..
You can just remember the first item, clear everything and then put that remembered item back.
ListItem first = drpAddressTypes.Items[0];
drpAddressTypes.Items.Clear();
drpAddressTypes.Items.Add(first);
drpAddressTypes.Items.RemoveRange(1, drpAddressTypes.Count - 1)
Something like?
Items.RemoveRange(drpAddressTypes.Items.Skip(1))

how do i prevent multiple instances of added rows in a listview?

List itemsToMove = new List();
foreach (ListViewItem item in lvScanRepository.SelectedItems)
{
itemsToMove.Add(item);
}
foreach (ListViewItem item in itemsToMove)
{
if (!lvBatch.Items.Contains(item))
{
lvScanRepository.Items.Remove(item);
lvBatch.Items.Add(item);
}
}
A ListViewItem can't belong to more than one ListView at the same time, so this condition:
if (!lvBatch.Items.Contains(item))
... will always be true.
What criteria do you want to use to determine whether the item in one ListView is "similar" to an item in another? Depending on that, you have a couple of options:
ListViewItem has a property called Name which can be used to uniquely identify items in a ListView. You can then call Items.ContainsKey(String) to see if an item exists with that name.
Alternatively you can search in lvBatch to find an item with the same Text as the one you're trying to add:
if (!lvBatch.Items.Cast<ListViewItem>().Any(i => i.Text == item.Text))
(You need to cast because ListViewItemCollection doesn't actually implement IEnumerable<ListViewItem>.)

Categories