Click here to Skip to main content
15,904,494 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi! i dont understand why this doesn't work correctly...

can you please check the error with this one?

C#
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
Updated 2-May-11 5:42am
v3

Try this:

C#
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)
 
Share this answer
 
v3
Comments
Niklas L 2-May-11 14:24pm    
Backwards is the key to success :) Fived.
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.
 
Share this answer
 
Comments
Kim Togo 2-May-11 12:29pm    
My 5. Nice catch!
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?
 
Share this answer
 
Comments
Member 7838027 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 2-May-11 11:42am    
Er: no.
if(gvList.Items[a]==gvList.SelectedItems[a])
Member 7838027 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900