Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# list delete
hi! i dont understand why this doesn't work correctly...
 
can you please check the error with this one?
 
int a=0;
int b=0;
while(gvList.SelectedItems.Count>0)
{
    if(gvList.Items[a]==gvList.SelectedItems[b])
    {
        myList.RemoveAt(a);
    }
    else
    {
        a++;
    }
}
 
//gvList is a gridview
//myList is a list. it is the itemsource of gvList
Posted 2-May-11 6:20am
Edited 2-May-11 6:42am
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Try this:
 
for (int i = 0; i < gvList.SelectedItems.Count; i++)
{
    gvList.Items.Remove(gvList.SelectedItems[i]);
}
gvList.SelectedItems.Clear();
 
(you may have to traverse the SelectedItems collection backwards)
  Permalink  
v3
Comments
Niklas Lindquist at 2-May-11 14:24pm
   
Backwards is the key to success :) Fived.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Since gvList.SelectedItems is never changed, its Count will never change, so you will never exit the while loop.
 
You should explain what you want to do and we will maybe find a solution.
  Permalink  
Comments
Kim Togo at 2-May-11 12:29pm
   
My 5. Nice catch!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Well several reasons really:
 
What happens if the selected items don't exactly match your list?
What happens to "b"?
What happens if the first item in gvList is not selected?
 
Which error did you mean?
  Permalink  
Comments
Member 7838027 at 2-May-11 11:32am
   
it's not possible that a selected item is not on the list because selecteditems are those items in the list whose checkbox is checked.
 
if the first item is not selected, the index (a) will increment and compare item at that index with the item at index b.
 
am i right?
OriginalGriff at 2-May-11 11:42am
   
Er: no.
if(gvList.Items[a]==gvList.SelectedItems[a])
Member 7838027 at 2-May-11 11:44am
   
i'm sorry for that... i already updated the code.... it was a typo

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 250
1 Jochen Arndt 155
2 PIEBALDconsult 150
3 DamithSL 125
4 Afzaal Ahmad Zeeshan 120
0 OriginalGriff 5,695
1 DamithSL 4,591
2 Maciej Los 4,012
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,190


Advertise | Privacy | Mobile
Web03 | 2.8.141220.1 | Last Updated 2 May 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100