Clearing textboxes..

  • Thread starter Thread starter Serdar C.
  • Start date Start date
S

Serdar C.

hi there, i am writing a program with LOTS of textboxes in it.. my problem
is when i try to clean the textboxes with foreach it gives error.. heres how
my code looks like:

private void ClearText ()

{
foreach (textbox t in this.controls)
{
t.text = ""
}
}

but it doesnt work! it was working quite good on visual basic.net but this
code seems not working with c#?!
 
Not all the controls in this.Controls are TextBox controls. When you
iterate through them, you get an InvalidCastException because a non-TextBox
control is being assigned to t, a TextBox variable.

foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox t = (TextBox) c;
t.Text = "";
}
}
 
Scott said:
Not all the controls in this.Controls are TextBox controls. When you
iterate through them, you get an InvalidCastException because a non-TextBox
control is being assigned to t, a TextBox variable.

foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox t = (TextBox) c;
t.Text = "";
}
}

Couldn't you do:

foreach (TextBox t in this.Controls)

?
 
No. The foreach command will iterate through ALL the objects in the
Controls collection and attempt to cast them to a TextBox. If any of them
aren't a TextBox, then an InvalidCastException will occur. Declaring the
type of variable as TextBox doesn't filter the contents of Controls
(although that would be really nice).
 
hi there, i am writing a program with LOTS of textboxes in it.. my problem
is when i try to clean the textboxes with foreach it gives error.. heres how
my code looks like:

private void ClearText ()

{
foreach (textbox t in this.controls)
{
t.text = ""
}
}

but it doesnt work! it was working quite good on visual basic.net but this
code seems not working with c#?!

Your syntax is correct, but C# is case sensitive. here is the code
toy should use.

foreach(TextBox c in this.Controls)
{
c.Text = null;

}


Otis Mukinfus
http://www.otismukinfus.com
 
foreach(object c in this.Controls)
{
if(c.GetType() == typeof(TextBox))
{
TextBox t = (TextBox)c;
t.Text = null;
}
}

Sorry Y'all above is the text that works for mixed controls...


Otis Mukinfus
http://www.otismukinfus.com
 
Back
Top