Type Comparison

  • Thread starter Thread starter Spencer Wasden
  • Start date Start date
S

Spencer Wasden

I want to determine if a control on a form is a TextBox type. I would like
to do something like the following WITHOUT doing a string comparison.

foreach (Control c in this.Controls){
if (c.GetType().ToString() == "System.Windows.Forms.TextBox" ){
MessageBox.Show(c.Text);
}
}


Is this possible?

Thank you
 
Spencer,

You can do this:

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

Hope this helps.
 
Mattias Sjögren said:
Sure:

if (c is TextBox)

Am I right in thinking the different between this, and the method Nicholas
Paldino posted:
if (c.GetType() == typeof(System.Windows.Forms.TextBox))

is that one the first will also return true for things that inherit from
TextBox?

Are there likely to be any performance differences? (If you're doing this
for a large collection of controls, any time saved would be increased!)
 
Danny,

My method will check against the textbox class, but will not check for
classes that derive from TextBox (which is the behavior of your original
post).

The one that Mattias and Rakesh posted (using is) will check for classes
that derive from TextBox as well.
 
Nicholas Paldino said:
My method will check against the textbox class, but will not check for
classes that derive from TextBox (which is the behavior of your original
post).

It wasn't my original post, I just butted in because I was curious :o)
 
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(System.Windows.Forms.TextBox )
{
MessageBox.Show(c.Text);
}
}

HTH

Ollie Riches
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top