Using TypeOf?

L

Leon

I have a program that fill 6 textbox on button click, but when using TypeOf
my program is trying to also fill label controls which throws my array out
of range. how can use TypeOf to only read textbox Control?

Piece of Code:

Dim I As Integer

For I = 0 To Me.Controls.Count - 1

If (TypeOf Controls(I) Is TextBox) Then

Dim tbox As TextBox = CType(Controls(I), TextBox)

tbox.Text = arr1(I)

End If

Next
 
H

Henri

It's not a matter of TypeOf, it's the way you're using "i" that is wrong:

Dim i As Integer = 0

For j As Integer = 0 To Controls.Count - 1
Dim ctrl As Control = Controls(j)
If TypeOf ctrl Is TextBox Then

DirectCast(ctrl, TextBox).Text = arr1(i)

i += 1

End If

Next
 
H

Henri

Better:

Dim i As Integer = 0

For Each ctrl As Control In Controls

If TypeOf ctrl Is TextBox Then

DirectCast(ctrl, TextBox).Text = arr1(i)

i += 1

End If

Next
 
L

Leon

Thanks So Much Henri,
That most definitely solve my problem. Could you please explain to me in
details what I was doing wrong.
Thanks again!
 
H

Henri

Ok, imagine that you have to simplify 1 textbox, 1 label, then 1 textbox in
your Controls collection.
arr1's length should be 2 if it's the same as the number of textboxes.

Your code:

Dim I As Integer
For I = 0 To Me.Controls.Count - 1
If (TypeOf Controls(I) Is TextBox) Then
Dim tbox As TextBox = CType(Controls(I), TextBox)
tbox.Text = arr1(I)
End If
Next

Let's trace the for...next loop in your code:

first iteration:
i = 0
typeof controls(0) is TextBox -> tbox.Text = arr1(0)

2nd iteration:
i = 1
typeof controls(1) is Label -> do nothing

3nd iteration:
i = 2
typeof controls(2) is TextBox -> tbox.Text = arr1(2) OUT OF RANGE
EXCEPTION!

Do you understand your mistake? The index you use to loop through the
Controls collection must be separated from the one you use to access arr1.

Henri
 
M

Matt Berther

Hello Henri,

Better yet (no type checking and casting, since the foreach can do this for
you)...

foreach (TextBox ctrl in Controls)
{
ctrl.Text = arr1;
i++;
}
 
H

Henri

Hello Matt,

But what happens if Controls also contains controls different from TextBox?

Henri

Matt Berther said:
Hello Henri,

Better yet (no type checking and casting, since the foreach can do this for
you)...

foreach (TextBox ctrl in Controls)
{
ctrl.Text = arr1;
i++;
}

--
Matt Berther
http://www.mattberther.com
Better:

Dim i As Integer = 0

For Each ctrl As Control In Controls

If TypeOf ctrl Is TextBox Then

DirectCast(ctrl, TextBox).Text = arr1(i)

i += 1

End If

Next
 

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,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top