How to solve GetType() error for abstract class ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi
I have one panel. It have 2 labels control and one abstract class control. In one event
I want to remove all labels control from that panel.
So I use this way.

foreach (Control c in this.panel1.Controls)

if (c.GetType()==typeof (System.Windows.Forms.Label )

this.panel1.Controls.Remove (c);



It work for label control. But it not work for my abstract controls
Error is "object reference is not set to an instance of an object
How to slove that kinds of problem? please show me the way

Thanks in Advanced
 
If it is "abstract" how can you even instantiate it? And if you cannot instantiate it, how can you add it to the controls collection? Do you mean an implementation of an abstract control? In that case, when you use GetType compare with the type of the implementation and not with the type of the abstract..

public abstract class SomeAbstractControl : Contro



public class ControlImplementation : SomeAbstractContro



if (control1.GetType() == typeof(ControlImplementation)) should work

Same for this: if (control1 as ControlImplementation != null

hope this helps

iulia
 
Hi, Stoitcho Goutsev

if( c.GetType()==typeof (System.Windows.Forms.Label ))

That line throw error.

In my panel, I have 3 controls, two are label type and one is abstract class control.
first 2 is ok. The third looping ,at the time of abstract class control c.GetType() throw error.
Because that control have no object. That control use singleton design. I want to skip that kind
of c.GetType() problem for that control.

Regards,
 
Hi Htun,

I can't quite understand what you mean by "... one is abstract class
control...".
In the Controls collection you don't have classes you have references to
instances of classes. An instance cannot be abstract.
As long as c (in your example) is not null you can't have GetType throwing
exception, but you cannot have a *null* item in the Controls collection,
either. So, I don't get it.

Can you reproduce the problem in an example?
 
Back
Top