How to loop thru all textboxes on form?

V

VB Programmer

How can I loop thru all textboxes on a form?

I want to remove any single quotes in the data entry. I was thinking
something like this:

For Each c As Control In Me.Controls
Dim t As TextBox = CType(c, TextBox)
t.Text = t.Text.Replace("'", "")
Next

But the CType is giving me a 'Specified cast is not valid'.

Thanks.
 
N

nmosafi

Your page will contain many controls, so you have to check each
control's type before you can cast to a textbox. You can use the "Is"
operator - in C# it would look like:

if (c is TextBox) {
TextBox t = (TextBox) c;
t.Text = t.Text.Replace ("'", "");
}

but I dont know VB syntax.

An alternative would be to surround the statement in a try/catch
statement and catch the InvalidCastException and continue the loop,
however it's usually better to check for expected exceptions.
 
J

John Spiegel

Hey,

A couple ideas:

Use the GetType() method to then test whether or not it is of type TextBox,
only taking action if it is.

A bit more brute force would be to wrap it in a try...catch and check for
the invalid cast, but that's not too pretty.

- John
 
K

Karl Seguin

What everyone else said is accurate, but I wanted to point out that you'll
need to recursively scan through all controls - your code doesn't show that
you are doing this (doesn't show that you aren't either).

private sub StripFromTextbox(parent as Control, searchFor as string,
replaceWith as string)
for each c as control in parent
if c.HasControls then
StripFromTextbox(c, searchFor, replaceWith)
end if
if c is TextBox then
dim t as textbox = ctype(c, textbox)
t.text = t.text.replace(searchFor, replaceWith)
end if
end sub

or something to that effect...

Karl
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top