Question tabcontrol1.tabpages.remove (Not working in a particular event)

mahe.helal

New member
Joined
Jun 15, 2010
Messages
3
Programming Experience
Beginner
hi,
I have an event called "worksheet_selectionchanged" which occurs when a range/cell is selected in an excle file.When the event is triggered, all the tabpages in a tabcontrol should be removed.

The code is given below:

VB.NET:
Private Sub myWorksheet_SelectionChange(ByVal Target As Excel.Range) Handles myWorksheet.SelectionChange

for each tabpagesToRemove as TabPage in tabcontrol1.tabpages
tabcontrol1.tabpages.remove(tabpagesToRemove)
next

end sub
but when ever i select a cell in the excel file, the tabpages seems to be "not removed".

Can anyone please help?
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,322
Location
Sydney, Australia
Programming Experience
10+
You cannot change a collection while enumerating that collection, i.e. in a For Each loop. If you want to remove all items then use the Clear method. If you want to remove specific items then you need to use a different method, e.g. a For loop backwards or a Do loop.
 

mahe.helal

New member
Joined
Jun 15, 2010
Messages
3
Programming Experience
Beginner
actually it works with "for each" loop using tabpages.remove.

but the point is when i put the code in form_load subroutine then it works.Again if I write the code in worksheet_selectionChanged event then it stops working.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,322
Location
Sydney, Australia
Programming Experience
10+
The rule is that you do NOT use a For Each loop if you want to change the collection. Stick to that rule and you'll be OK. I don;t see how it could work at all but, even if it does, it won't work all the time, as you've discovered, so just don't do it at all and you won't have a problem. There are other options that are barely harder if at all.
 

mahe.helal

New member
Joined
Jun 15, 2010
Messages
3
Programming Experience
Beginner
well i tried with the othe options as well but i get the same result here also.

Let me describe the scenarios:

When i select a cell in an excel file, a form suppose to show up which contains a tabcontrol with some tabpages.but all the tabpages has to be hidden since i can't use
VB.NET:
tabpages.hide()
method I intend to use the
VB.NET:
tabcontrol.tabpages.remove(tabpage)
method.
 
Top Bottom