listbox selecteditems cannot be removed due to using ItemsSource - c#

I need you to help fix my issues. When I use listbox ItemSource in my code, selected items cannot be allowed to remove. Without using ListBox ItemsSource, the remove operation is working. Why? Please give me your soultion code. I need to include ItemsSource for the listbox. Thanks a million times! Oh yes I am using C# 4.5 and WPF.
public SendEmail(List<string> items, ItemCollection needsItems)
: this()
{
_needList = needsItems;
lstNeeds.ItemsSource = _needList;
}
//Remove selected Items not working
if (lstNeeds.SelectedItem != null)
{
for (int i = lstNeeds.SelectedItems.Count - 1; i >= 0; i--)
{
lstNeeds.Items.Remove(lstNeeds.SelectedItems[i]);
}
}

You're trying to remove an item from the collection you're iterating over.

Try this:
if (lstNeeds.SelectedItem != null)
{
List<Int32> selIdx = new List<Int32>();
foreach (var item in lstNeeds.SelectedItems)
selIdx.Add(lstNeeds.Items.IndexOf(item);
selIdx.Sort(); //necessary?
for (Int32 idx = selIdx.Count - 1; i >= 0; i--)
{
lstNeeds.Items.RemoveAt(selIdx[i]);
}
}

Related

C# for loop skipping last item

I have the below for loop
int listCount = _itemCollection.Count;
//_itemCollection is of type SPListItemCollection
for (int i=0;i<listCount;i++)
{
var item = _itemCollection[i]; // just to prevent changes in all places inside the for loop
if(item['expirydate']>today){
item.delete();
listCount--; //as I am removing 1 item, I am decrementing count
}
}
In this for loop, I am iterating through the items in itemcollection and deleting some of them. i.e item will be removed from itemcollection array and so itemcollection.count will be reduced by 1
This is not deleting the 3rd item every time, when I have 3 items to delete
I am not sure what condition should be used for getting it right
You should go in the reverse order as below and use for instead of foreach as below.
int listCount = _itemCollection.Count;
for (int i = listCount - 1; i >= 0; i--)
{
var item = _itemCollection[i]; // just to prevent changes in all places inside the for loop
if(item['expirydate'] > today){
item.delete();
}
}
You can do something like this:
_itemCollection.RemoveAll(item => item['expirydate'] > today);
This removes all the items that matches the given condition.
To remove item from SPListItemCollection check this documentation
Try this:
int listCount = _itemCollection.Count;
for (int i = 0; i < listCount; i++)
{
var item = _itemCollection[i];
if(item [expirydate] > today)
{
_itemCollection.Remove(item);
listCount--;
}
}
This may fulfill your want. Here you can directly use _itemCollection[i] instead of item.
I hope this may help you. Enjoy coding.

Loop through wpf listbox using a for loop instead of a foreach loop

I have a c# wpf listbox and I am trying to get the values from the selected items. I cannot use a foreach loop (every value I find will remove an item from the listbox). But this seems impossible.
What I want is somthing like this:
for (int i = <numberofselecteditems> - 1; i >= 0; i--)
{
string displaymembervalue = listbox.selecteditem[i].displaymembervalue;
}
I have a solution which involve to loop over all the listbox items twice. This is not really an option since it will slow the app too much.
Like I said before, this is NOT the
System.Windows.Forms.Listbox
but the
System.Windows.Controls.Listbox
thank you!!
J.
See the solution here, it is essentially using a foreach in the follolwing fashion:
foreach (var item in listBox1.SelectedItems)
{
// Do what you want here... Console.WriteLine(item), etc.
}
If you really want to do it with a for loop rather than a foreach, then do the following:
for(int i = selectedItems.Count - 1; i >= 0; --i)
{
var item = selectedItems[i];
// Do what you want with item
}
Here is your XAML bound to a Observable collection
<ListBox ItemsSource="{Binding items}"/>
Here is your observable collection of objects
private ObservableCollection<Object> _items;
public ObservableCollection<Object> items{
get{ return _items; }
}
Here is the enumeration over them and the removing of each item
for(int x = 0; x < _items.Count; x++){
_items.Remove(_items.Where(n => n == _items[x]).Single());
//You may have to do a notify property changed on this if the UI Doesnt update but thats easily googled.
//Traditionally it would update. However since you are bound to items Im not sure if it will update when you manipulate _items
}
Create a second list. You still have to iterate twice, but the second iteration is not over the entire list of items.
var items List<ListBoxItem>;
foreach (var item in listbox1.SelectedItems)
items.Add(item);
foreach (var item in items)
listbox1.Remove(item);
Alternatively instead of enumerating twice you can create a copy of the list of objects and then remove the items from the original list while still enumerating.
foreach (var selectedItem in listBox1.SelectedItems.Cast<List>())
{
//remove items from the original list here
}

Prevent Certain Items from Being Deleted in ListBox

So here is the code I have the allows me to delete selected items in my listbox.
ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstOutput);
selectedItems = lstOutput.SelectedItems;
if (lstOutput.SelectedIndex != -1)
{
for (int i = selectedItems.Count - 1; i >= 0; i--)
lstOutput.Items.Remove(selectedItems[i]);
}
else
MessageBox.Show("Debe seleccionar un email");
The problem is that I have labels at the top that show what the output is. I also have statistics at the bottom of the page. The way the code is now, I am able to delete those, which I don't want. I am unsure of how to prevent these from being deleted.
first of all the fire line is unneeded and you can merger the two first line to:
ListBox.SelectedObjectCollection selectedItems = lstOutput.SelectedItems;
now for the remove of the item that you want to keep. you can make a condition.
for (int i = selectedItems.Count - 1; i >= 0; i--)
{
if(selectedItems[i] is /*here is where you come and check if the current selected item is of the type you don't want to delete*/)
lstOutput.Items.Remove(selectedItems[i]);
}
if you'll tell me what's the type of the "labels at the top" and "statistics at the bottom" i'll put it in the answer
EDIT
in similar to what you said you can do:
List<object> fixedItems = new List<object>();
fixedItems.Add(/*Your labels and statistics*/);
and then do
for (int i = selectedItems.Count - 1; i >= 0; i--)
{
if(fixedItems.Contains(selectedItems[i]) == false)
lstOutput.Items.Remove(selectedItems[i]);
}
for the list you'll need to add
using System.Collections.Generic;
at the beginning of the page

WPF DataGrid Remove SelectedItems

Recently I've been working on a project which imports data programmicaly into a WPF DataGrid.
I'm almost done with the project but the thing that I left out was a button to remove selected cells and this is where I'm stuck!
I wrote this code using my basic knowledge of DataGrids:
var grid = dataGrid1;
if (grid.SelectedIndex >= 0)
{
for (int i = 0; i <= grid.SelectedItems.Count; i++)
{
grid.Items.Remove(grid.SelectedItems[i]);
};
}
Works fine on removing only the item selected just like CurrentItem but it doesn't remove anymore than 2 selected items!
The DataGrid I have should at least contain a minimum of 100 items. I've added a remove all option but this is also necessary.
I'll be thankful if anyone gives me the solution.
By removing selected item you are changing SelectedItems collection. You should copy it first and then start removing.
This also worked well for me.
while (dataGrid1.SelectedItems.Count > 0){
dataGrid1_item_source.Rows.RemoveAt(dataGrid1.SelectedIndex);
}
The mistake you are doing here you are removing items during loop whaich is messing with loop count so make a copy grid and remove selecteditem from it and then equlize it by the orignal one..
Check this out
var grid = dataGrid1;
var mygrid = dataGrid1
if (grid.SelectedIndex >= 0)
{
for (int i = 0; i <= grid.SelectedItems.Count; i++)
{
mygrid .Items.Remove(grid.SelectedItems[i]);
};
}
grid = mygrid;
This worked for me...
while (dataGrid1.SelectedItems.Count > 0){
dataGrid1_item_source.Rows.RemoveAt(dataGrid1.SelectedIndex);
}
This worked for me...
if (DataGrid1.SelectedItem != null)
{
((DataRowView)(DataGrid1.SelectedItem)).Row.Delete();
}
A while loop using the SelectedItem instead of the SelectedIndex
while (dataGrid1.SelectedItems.Count > 0){
if (dataGrid1.SelectedItem == CollectionView.NewItemPlaceholder)
dataGrid1.SelectedItems.Remove(grid.SelectedItem);
else
dataGrid1.Items.Remove(dataGrid1.SelectedItem);
}
I have stack with the same problem as an author. And found quite beautiful (I think) solution.
And so the main problem is that the SelectedItems dynamic, and when you delete one row, it is recalculated again.
And so my code looks like this:
for (int i = -datagrid1.SelectedItems.Count; i < datagrid1.SelectedItems.Count; i++)
{
datagrid1.SelectedItems.RemoveAt(datagrid1.SelectedIndex);
}
So, every time the for loop is doing step 1, datagrid1.SelectedItems.Count is decreased by 1, and the variable i increases.
Do While dgData.SelectedItems.Count > 0
dgData.SelectedItem.Row.Delete()
Loop
My solution (if you are using adonet with autogeneratecolumns=true);
for (int i = dgv.SelectedItems.Count-1; i >= 0; i--)
{
DataRowView dataRow = (DataRowView)dgv.SelectedItems[i];
dataRow.Delete();
}

Remove selected rows from multi-column listView

I have a listview with two columns and I'm using a context menu to allow users to remove selected rows. To remove the selected rows, I've tried with the following code but it doesn't work:
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
listView1.SelectedItems.Clear();
}
I suspect this is because the listview has two columns, but I can't figure out a solution to remove selected rows. Removing all rows works with: listView1.Items.Clear();.
The latest example of BeefTurkey looks correct, but he should decrement the variable i after removing a selected item:
for (int i = 0; i < listView1.Items.Count; i++ )
{
if (listView1.Items[i].Selected)
{
listView1.Items[i].Remove();
i--;
}
}
The index of items larger as i is decremented by 1 after the removal. So you should reposition i to match the next not tested item.
while (listBox1.SelectedItems.Count > 0)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
foreach(ListViewItem lvItem in lvDocument.SelectedItems)
{
lvDocument.Items.Remove(lvItem);
}
This seems to work:
for (int i = 0; i < listView1.Items.Count; i++ )
{
if (listView1.Items[i].Selected)
{
listView1.Items[i].SubItems.Clear();
}
}
Is there any way to remove items and re-order the listView so that there are no empty rows in the middle of other rows?
This seems to be a better solution:
for (int i = 0; i < listView1.Items.Count; i++ )
{
if (listView1.Items[i].Selected)
{
listView1.Items[i].Remove();
}
}
What you can do:
foreach (ListViewItem Item in LstvClients.Items)
{
if (item.Selected)
{
LstvClients.Items.Remove(Item);
}
}
(Yours is better, item.Remove())
I have been using something slightly different then the others to remove all the selected items from a ListView control:
foreach (ListViewItem listViewItem in listView1.SelectedItems)
{
listView1.Items.Remove(listViewItem);
}
I'm not sure how this would match up performance-wise to the other posted methods on large lists, but I think it is a little cleaner looking in cases where that isn't an issue.
This is the correct way to remove all selected items. The method is to always access fist selected item with an index 0 and loop until no more selected items left. You cannot refer to other items inside collection with an absolute index safely since indexes will change as soon as you delete one of the items.
while( listView1.SelectedItems.Count > 0)
{
listView1.Items.Remove(lvFiles.SelectedItems[0]);
}
do
{
this.listView1.CheckedItems[0].Remove();
} while (this.listView1.CheckedItems.Count > 0);
This works better

Categories