Using FOR to edit TextBoxes

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.
 
M

MatsL

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

//Mats
 
G

Guest

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
 
C

Cowboy \(Gregory A. Beamer\)

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().
 
J

Jl_G_0

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...
 

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

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top