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.
Related
May I know how can I identify the item in a SharePoint list view via an ID?
Due to some changes, I am unable to use foreach as in the situation where a row remains in the list, it resulted in repetitive processing of the same item.
Below is my code snippet and sample scenario.
foreach (SPListItem item in unprocessedView)
//list only contains items with "Processed" = false
{
//if "Type" = "report",
//set "Processed" = true.
//item does not appear in list anymore.
//if "Type" = "result"
//do nothing.
//item remains in list.
}
Let's say there are 2 items in unprocessedView.
1. result type.
2. report type.
With the conditions above, item 1. will not be processed, and remains in the list.
On the loop, 1. is processed again instead of moving on to item 2.
May I know how can I workaround this?
Thank you.
Modify the code snippet as below to make it works.
foreach (SPListItem item in unprocessedView)
{
if (item["Type"]!=null&&item["Type"].ToString() == "report")
{
item["Processed"] = true;
item.Update();
}
}
I have found many examples on how to find the selected items in a listbox and how to iterate through a listbox;
for(int index=0;index < listBox1.Items.Count; index++)
{
MessageBox.Show(listBox1.Items[index].ToString();
}
or
foreach (DataRowView item in listBox1.Items)
{
MessageBox.Show(item.Row["ID"].ToString() + " | " + item.Row["bus"].ToString());
}
While these methods work great for the selected items, what I have yet to figure out, or find, is how to get the selected state, selected and unselected, of every item in a listbox, as the above only gives the selected.
Basically, I need something like this;
for(int index=0;index < listBox1.Items.Count; index++)
{
if (index.SelectedMode == SelectedMode.Selected)
{
MessageBox.Show(listBox1.Items[index].ToString() +"= Selected";
}
else
{
MessageBox.Show(listBox1.Items[index].ToString() +"= Unselected";
}
}
I've found a snippet that said to use (listBox1.SelectedIndex = -1) to determine the selected state however I've not figured out or found how to build a loop around this to check each item in the listbox.
I've also read that I should put the listbox items into an array, but again nothing about getting the selected state of each item in the listbox.
I know I'll have to iterate through the listbox to accomplish what I'm needing, pretty sure it'll be one of the above loops, however I have yet to find how to extract the selected state of each item in the listbox.
I'm using VS2013, C# Windows Form, .NET Framework 4.0
Thanks in advance for any advice/direction.
This will get you the unselected items:
List<string> unselected = listBox1.Items.Cast<string>().Except(listBox1.SelectedItems.Cast<string>());
You can loop over that list like this:
foreach(string str in listBox1.Items.Cast<string>().Except(listBox1.SelectedItems.Cast<string>()))
{
System.Diagnostics.Debug.WriteLine($"{str} = Not selected");
}
I've made the assumption that you're using string as your item type. If you want to use something else then just replace string with your type and it should still work.
You then loop over the unselected items to do whatever you want with them then loop over listBox1.SelectedItems to do whatever you want with the selected ones.
You can use GetSelected method of the ListBox. It returns a value indicating whether the specified item is selected.
For example, the following code, sets the value of selected to true if the item at index 0 (the first item) is selected:
var selected = listBox1.GetSelected(0);
Example
Te following loop, shows a message box for each item, showing the item text and item selection status:
for (int i = 0; i < listBox1.Items.Count; i++)
{
var text = listBox1.GetItemText(listBox1.Items[i]);
var selected = listBox1.GetSelected(i);
MessageBox.Show(string.Format("{0}:{1}", text, selected ? "Selected" : "Not Selected"));
}
I have an IList which is a copy of SelectedItems within a DataGrid.
If I iterate through this IList and select an item. I am using a simple 'for()' statement to do this, instead of a 'foreach()' as I need the index.
How can then use this item to find the same item in the main items?
Let's say the third item out of SelectedItems is the one I'm trying to find, how do I find this in DataGrid.Items?
Same way as you find it in list
for(int i = 0; i < myDataGrid.Items.Count; i++)
{
if (((IList)myDataGrid.Items[i]) == myitem)
{
//Found Item
}
}
Make sure that the both are same instance, else it will always return false.
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);
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>.)