.NET Questions (CLOSED)

Questions and Answers on any aspect of .NET. Now closed.

This discussion group is now closed.

Have a question about .NET development? Try stackoverflow.com, a worldwide community of great developers asking and answering questions 24 hours a day.

The archives of .NET Questions contain years of Q&A. Even older .NET Questions are still online, too.

C# Removing

Hello, I'm trying to remove Controls from a Panel.

These panels are UserControls added to the project.

They are declared something like this:

public UC1 : UserControl
public UC2 : UserControl

This is the code:

foreach ( Control c in this.panelX.Controls ) {
  if ( c.getType().ToString().Equals("UserControl") ) {
    this.panelX.remove(c);
  }
}

The problem is that the c.getType().ToString() method calls returns the lowest name, "UC1" or "UC2". I would like to have a way to compare them at the higher level class, "UserControl".

Can someone help with this?

Thanks.
KrazyMane
Friday, November 09, 2007
 
 
Well I solved it, using

UserControl userControl = c as UserControl;

within the foreach and then use panelX.controls.remove to remove the userControl object  from the panel.

Thanks.
KrazyMane
Friday, November 09, 2007
 
 
You can also use the "is" keyword.

if (control is UserControl)
{
  .... do something...
}

As you've seen the "as" keyword attempts a cast to the type specified and returns null if it fails (instead of throwing an exception).
anon
Friday, November 09, 2007
 
 
Is it really safe to use remove inside a foreach loop?
as
Sunday, November 11, 2007
 
 
"Is it really safe to use remove inside a foreach loop? "

Good point. No it's not. You should never remove items from a collection that you are iterating with a foreach loop. The OP should use a standard for loop instead. Just be sure to decrement the loop counter after removing any controls:

Control c;
for (int i = 0; i < this.Controls.Count; i++)
{
    c = this.Controls[i] as UserControl;
    if (c != null)
    {
        this.Controls.RemoveAt(i);
        i--;
    }
}
anon
Sunday, November 11, 2007
 
 
Thanks guys/gals. The foreach was actually causing some problems so I came back here to check on the replies and there was the comment about foreach not being good for collection removal. Thanks.
KrazyMane
Monday, November 12, 2007
 
 
A slightly simpler approach than fiddling with the iterator:  start at the end of the collection and work backwards:

for (int i = Controls.Count - 1; i < 0; i--)
{
  Controls.RemoveAt(i);
}
Robert Rossney Send private email
Monday, November 12, 2007
 
 
I think you can also use:

c.GetType().IsSubclassOf(UserControl)

Tuesday, November 13, 2007
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz