How to loop through textboxes?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
B

Brett Romero

I'd like to loop through all text boxes on a winform and check if they
are empty.

private bool emptyTextBoxes()
{
bool isEmpty = true;

foreach(Control ctl in Controls)
{
if (typeof(ctl) == TextBox) //error here
if(ctl.Text != "")
isEmpty = false;
}
return isEmpty
}

I get this error:
The type or namespace name 'ctl' could not be found (are you missing a
using directive or an assembly reference?)

ctl is a typeof Control and I want to make sure it is a TextBox. Why
is this wrong?

Thanks,
Brett
 
Two things.

First of all, typeof() converts a _class name_ into a Type object, so
it's expecting a type name there, for example typeof(TextBox), not a
variable.

In order to get the type of the object referenced by a variable, call
the GetType() method:

ctl.GetType()

Second, there is a much better construct for what you're trying to do:

foreach(Control ctl in Controls)
{
TextBox box = ctl as TextBox;
if (box != null)
{
if (box.Text.Length > 0)
{
isEmpty = false;
}
}
}
 
Second, there is a much better construct for what you're trying to do:

foreach(Control ctl in Controls)
{
TextBox box = ctl as TextBox;
if (box != null)
{
if (box.Text.Length > 0)
{
isEmpty = false;
}
}
}

I would also add that you might want to add some recursion to check child
controls... things like groupBoxes and Panels.

public void DoSomething(TextBox tb)
{
if (tb.Text.Length == 0)
{
...
}
}

public void CheckTextBoxes(ControlCollection ctrls)
{
if (ctrls == null) return;
foreach(Control c in ctrls)
{
if (c is TextBox) DoSomething((TextBox)c);
else CheckTextBoxes(c.Controls);
}
}

-mdb
 
Change:

if (typeof(ctl) == TextBox)

to

if (ctl.GetType() == typeof(TextBox))

and it should work fine.

Dave
 
Change:

if (typeof(ctl) == TextBox)
to
if (ctl.GetType() == typeof(TextBox))

and it should work fine.

Well, it'll work subtly differently to using "as" or "is". The above
would return false if you had a control which was derived from TextBox.
Now, it could be that that's what's actually wanted - but it usually
isn't.

Using as/is is generally preferrable, IMO.

Jon
 

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