473,776 Members | 1,665 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Programically remove controls

Hi,

My code below doesn't work does anyone have any pointers? All my controls
are programically added.

Dim i As Int16
For i = 0 To Me.Controls.Cou nt - 1
If Me.Controls(i). Name <> "TheOneIWantToK eep" Then
Me.Controls.Rem oveAt(i)
End If
Next

As the loop moves through the index I get an Index Is Out Of Range Error mid
way through.

Many thanks
Nov 20 '05 #1
9 15343
Hello,

"Merlin" <je**@jg-tech.co.uk> schrieb:
My code below doesn't work does anyone have any
pointers? All my controls are programically added.

Dim i As Int16
For i = 0 To Me.Controls.Cou nt - 1
If Me.Controls(i). Name <> "TheOneIWantToK eep" Then
Me.Controls.Rem oveAt(i)
End If
Next

As the loop moves through the index I get an Index Is
Out Of Range Error mid way through.


The problem is that after removing a control from the Controls collection
there are fewer controls in this collection.

HTH,
Herfried K. Wagner
--
MVP · VB Classic, VB .NET
http://www.mvps.org/dotnet
Nov 20 '05 #2
"Merlin" <je**@jg-tech.co.uk> schrieb
Hi,

My code below doesn't work does anyone have any pointers? All my
controls are programically added.

Dim i As Int16
For i = 0 To Me.Controls.Cou nt - 1
If Me.Controls(i). Name <> "TheOneIWantToK eep" Then
Me.Controls.Rem oveAt(i)
End If
Next

As the loop moves through the index I get an Index Is Out Of Range
Error mid way through.


For i = Me.Controls.Cou nt - 1 To 0 step -1
--
Armin
Nov 20 '05 #3
Cor
nice
Nov 20 '05 #4
> Dim i As Int16
For i = 0 To Me.Controls.Cou nt - 1
If Me.Controls(i). Name <> "TheOneIWantToK eep" Then
Me.Controls.Rem oveAt(i)
End If
Next

As the loop moves through the index I get an Index Is Out Of Range Error mid way through.


Because the controls are being deleted as you traverse the collection, the
index sooner or later becomes invalid. The safest way is to use a For...Each
Loop:

Dim ThisCtrl as Control

For Each ThisCtrl in Me.Controls
Me.Controls.Rem ove( ThisCtrl )
Next

HTH

~
Jeremy

"Knowing others is intelligence;
knowing yourself is true wisdom.
Mastering others is strength;
mastering yourself is true power."
-Lao Tzu

Nov 20 '05 #5
Cor
For Each ThisCtrl in Me.Controls
if ThisCtrl.Name <> "TheOneIWantToK eep" Then Me.Controls.Rem ove(
ThisCtrl )
Next

But I find the one from Armin nice too.
Nov 20 '05 #6
Jeremy,
Because the controls are being deleted as you traverse the collection, the
index sooner or later becomes invalid. The safest way is to use a For...Each Loop: For each & removing items from a collection are normally incompatible!
Control.Control s happens to be an exception. Well partial exception, it
doesn't work correctly. If you start relying on this pattern, it will bite
you later! (Try it on a HashTable or ArrayList).

Try a for each loop on an inherited form, a number of controls are not
deleted! Some from the base, some from the derived form!

Try the follow, you will get an Invalid Operation Exception "Collection was
modified; enumeration operation may not execute".

Dim list As New ArrayList
list.Add("a")
list.Add("b")
list.Add("c")
Dim item as Object
For Each item In list
list.Remove(ite m)
Next

I would recommend Armin's method or a Do While loop, neither will receive
the above exception, and they both remove all the controls!

Do While Me.Controls.Cou nt <> 0
me.controls.Rem oveAt(0)
Loop

Of course Armin's may be more efficient as he is removing from the end of
the collection, while above I am removing from the beginning.

You could use:
me.controls.Rem oveAt(me.contro ls.count -1)

to remove from the end.

Of course we all missed the sure fire way to remove all the controls.

Me.Controls.Cle ar()

Hope this helps
Jay

"Jeremy Cowles" <jeremy.cowle s[nosp@m]asifl.com> wrote in message
news:L7******** ***********@twi ster.tampabay.r r.com...
Dim i As Int16
For i = 0 To Me.Controls.Cou nt - 1
If Me.Controls(i). Name <> "TheOneIWantToK eep" Then
Me.Controls.Rem oveAt(i)
End If
Next

As the loop moves through the index I get an Index Is Out Of Range Error

mid
way through.


Because the controls are being deleted as you traverse the collection, the
index sooner or later becomes invalid. The safest way is to use a

For...Each Loop:

Dim ThisCtrl as Control

For Each ThisCtrl in Me.Controls
Me.Controls.Rem ove( ThisCtrl )
Next

HTH

~
Jeremy

"Knowing others is intelligence;
knowing yourself is true wisdom.
Mastering others is strength;
mastering yourself is true power."
-Lao Tzu

Nov 20 '05 #7
> > Because the controls are being deleted as you traverse the collection,
the
index sooner or later becomes invalid. The safest way is to use a For...Each
Loop:

For each & removing items from a collection are normally incompatible!
Control.Control s happens to be an exception. Well partial exception, it
doesn't work correctly. If you start relying on this pattern, it will bite
you later! (Try it on a HashTable or ArrayList).

Try a for each loop on an inherited form, a number of controls are not
deleted! Some from the base, some from the derived form!


I _NEVER_ use visual inheritance (soooo buggy), I leave that up to the Beta
testers.

=)

Sorry about the oversight.

Of course we all missed the sure fire way to remove all the controls.
Me.Controls.Cle ar()


Nice (duh!).

~
Jeremy

Nov 20 '05 #8
Cor
Jay,
I was writing "I was looking at it and thought of methode like you, then
came the methode from Armin and I did think Yeah that's it in this case"
The problem is that one control has to stay and you don't know which.
Now I am in doubt, but have a while no time.
I am curious if the sollution is there when I come back, otherwise I go look
for it.
Cor
Nov 20 '05 #9
Cor
Jay, Armin, Jeremy, Merlin,
I did test all the methodes
I did it with a button on which event the procedure started.
The only one which works fine is the one from Armin.
The methode from Jay does absolute not work in this situation, but
because of his second answer he did know that of course already.
The methode from Jeremy throws an exeption
I did not test the second methode from Jay, I did only think about the
Treeview from Woody "Jjust remove it and add it, He kills you Jay :-)

Conclusion in my little test situation did only the methode from Armin works
fine.

Cor

Nov 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
20188
by: Charles Law | last post by:
I have a form on which user controls are placed at runtime. When a control is added to the form a handler is added for an event that a high-level object raises, which must be handled by the new control. When I close the form I am expecting that the control ceases to be. However, if my object raises the event after the form has been closed, I find that there is still a user control object that handles it. Clearly the user control has not...
2
1687
by: Daniel Friend | last post by:
Hello, I have added a custom usercontrol programically and all works fine... I would like to change some custom properties that I have set in that usercontrol. Any help would be greatly appreciated!!!! Thanks,
2
5043
by: Agnes | last post by:
In myDatagrid, there is 3 columns, account code, debit,credit. If the user input some particular a account code in column1 , i need to based on the contect of column1, to disable column2(debit),column3(credit) I try processcmdkey , onKeypress, onKeydown event already ( set e.handled = false , just like textbox event) However, it still let the user input anyfield ( after use press'tab', the field will gone blank) My aim is, user press any...
3
1812
by: Jim | last post by:
I have a datagrid with a DataAdapter as the DataSource. The user fills in their data for 3 columns and I want to programically add a value to the 4th (invisible) column (employee number). That way when the user saves the data I can use the data already in the datagrid. Typically the user will add several rows before the DataSet.HasChanges is called and the DataAdapter.Update(AllChanges) is called. I want to add an employee number to each...
2
1818
by: dtarczynski | last post by:
Hello. Im trying to add new EventHandler to DropDownList programically. Im doing something like this: DropDownList ddlCate = new DropDownList(); ddlCate.ID = String.Format("ddlCategory{0}", i++); ddlCate.DataSource = tblSub1; ddlCate.DataTextField = tblSub1.Columns.ColumnName; ddlCate.DataValueField =
5
2595
by: superjacent | last post by:
Hope someone can help. I have a saved parent form containing an unbound sub-form. I set the SourceObject (form) after the Parent Form opens/loads. The sub-form (datasheet view) basically displays the results of a cross-tab query The cross-tab query is created dynamically (in code) as the column headings are subject to change. I therefore have to create a new form (in code) and add the necessary
0
1233
by: abduzalam | last post by:
Hi Members, I am in a serious trouble,My problem is i want to develop a software as my academic project, it is network back up database, that is a remote machine hold sql databses, and when i send a request to the remote machine, the software finds the no.of databse (sql)in & it display in the local sys and want to backup and store in the local machine, so my qns is how programically backup and restore an sql databse...my front end...
1
3506
by: =?Utf-8?B?U3RlcGhhbmllIERvaGVydHk=?= | last post by:
Can anyone tell me how to programmatically remove a control from a tab page from VB .Net? The control was added using: Me.TabPage1.Controls.Add(pb) but I don't know what its index number is to remove it using: Me.TabPage1.Controls.RemoveAt(index) and Me.TabPage1.Controls.Remove(pb) doesn't work.
2
9093
by: =?Utf-8?B?R3JlZw==?= | last post by:
I have the following code the dynamically adds a specific number of controls. for x as integer = 1 to 10 Dim btn as Windows.Forms.Button = New Windows.Forms.Button btn.Name = "btn" & x btn.Text = "Test" & x controls.add(btn) next x This results in 10 buttons appearing on the screen. I've excluded the
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10061
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9923
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6722
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5368
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5497
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.