Using FOR to edit TextBoxes

  • Thread starter Thread starter Jl_G_0
  • Start date Start date
J

Jl_G_0

Hey all.

I have to check the content of 20 textboxes on my Page_Load event, to
remove the string "nbsp;" from them.
I do it with:
If TextBox1.Text = "nbsp;" Then
TextBox1.Text = ""
End If

Works, but I have a lot of lines on my code... Is there any way to do
a FOR Loop to do this. The Texboxes names are TextBox1 to TextBox20, so
I thought I could use the folllowing command inside the FOR loop:
(Beofre the FOR: Dim i as Integer...)

If TextBox+i = "nbsp;" ' ERROR HERE how to make something like this
work ?

Hoep its possible to do that... thx.
 
You should use FindControl(controlName) to do that.
like FindControl("TextBox" + i).Text = string.Empty;

//Mats
 
It's more efficient to loop over control collections once like that:
--- c# code---
foreach (Control control in this.Controls)
{
TextBox textBox = control as TextBox;
if (textBox != null && textBox.ID.StartsWith("TextBox"))
{
if (textBox.Text == " ")
textBox.Text = String.Empty;
}
}
-- end code ---
Milosz Skalecki
MCP, MCAD
 
You can go through the entire control hierarchy, but it is recursive, so you
have to check all containers for other controls (panels, etc.).

For each WebControl control in Container.Controls

Start with Container = Page.

You will also have to test each control to make sure it is a textbox, with
GetType().

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com

*************************************************
Think outside of the box!
*************************************************
 
Thx all for helping, managed to do it using:

Dim myTbox As TextBox
For i as Integer = 1 to 17
myTbox = FindControl("Text" & i)
If myTbox.Text = " "
myTbox.Text = ""
End If
Next

Thx again. Now I just use 7 lines of code to clean 17 textboxes...
 
Back
Top