all groups > asp.net webcontrols > october 2006 >
You're in the

asp.net webcontrols

group:

ControlCollection.Remove bug


ControlCollection.Remove bug Abraham Andres Luna
10/30/2006 2:57:58 PM
asp.net webcontrols:
hello everyone,

this code only removes the first HtmlMeta control even though i loop through
all of the controls:

<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(Object Sender, EventArgs E)
{
foreach (Control ctl in Page.Header.Controls)
if (ctl.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlMeta")
Page.Header.Controls.Remove(ctl);
}
</script>
<html>
<head runat="server">
<title>HtmlMeta Test Page</title>
<meta name="description" content="long description" />
<meta name="keywords" content="keyword list" />
</head>
<body>
Done!
</body>
</html>

thanks for any help with this.

Re: ControlCollection.Remove bug marss
10/31/2006 1:34:27 AM

Abraham Andres Luna =D0=BD=D0=B0=D0=BF=D0=B8=D1=81=D0=B0=D0=B2:
[quoted text, click to view]

"The foreach statement is used to iterate through the collection to get
the desired information, but should not be used to change the contents
of the collection to avoid unpredictable side effects..." (MSDN)

for(int i=3DPage.Header.Controls.Count-1; i>=3D0; i--)
if (Page.Header.Controls[i].GetType().ToString() =3D=3D
"System.Web.UI.HtmlControls.HtmlMeta")
Page.Header.Controls.RemoveAt(i);
Re: ControlCollection.Remove bug Alvin Chooi
10/31/2006 5:12:43 AM
You could only remove first HtmlMEta control is because when you are
deleting the first HtmlMeta Control, the ControlCollection in the
Page.Header will be reduced one, which would immediately out of the
foreach. What you need to do is use the for statement, minus one on
looping index whenever you call the Remove() method.


Hope this helps,


Alvin Chooi
Microsoft ASP.NET Enthusiast
http://alvinzc.blogspot.com
Re: ControlCollection.Remove bug Abraham Andres Luna
10/31/2006 8:08:44 AM
thanks so much for your reply. i will update my code accordingly.

[quoted text, click to view]

Abraham Andres Luna ???????:
[quoted text, click to view]

"The foreach statement is used to iterate through the collection to get
the desired information, but should not be used to change the contents
of the collection to avoid unpredictable side effects..." (MSDN)

for(int i=Page.Header.Controls.Count-1; i>=0; i--)
if (Page.Header.Controls[i].GetType().ToString() ==
"System.Web.UI.HtmlControls.HtmlMeta")
Page.Header.Controls.RemoveAt(i);

AddThis Social Bookmark Button