Saturday, March 24, 2012

loop through textboxes

I'm trying to loop through textboxes and see if there ID is equal to a string. If so, I want to get the value and put it in a sql string that i'm creating. Can someone look at the following loop and tell me what I'm doing wrong? Thanks!


Dim i as integer
For i=1 to 8
Dim lbDept as string, lbOpn as string
Dim ctl As Control
For Each ctl In Page.Controls
If TypeOf ctl Is TextBox Then
Dim tb as String = CType(ctl, TextBox).id
Dim tbval as String = CType(ctl,Textbox).text
If tb = "Dept" & i then label1.text = tbval
If tb = "Opn" & i then label2.text = tbval
End If
Next
i=i+1
Next
The reason it's not working as you expect is that Page.Controls does not containall of the server controls on the Page. It only contains theimmediate child controls. For example, the stuff in blueis part of the Page.Controls collection:
<html>
<head>
</head>
<body>
<form runat="server">
<asp:Panel id="MyPanel" runat="server"> <!-- this panel is within the FORM's Controls collection, not within the Page.Controls -->
<asp:Textbox id="MyTextbox" runat="server"> <!-- this textbox is within the PANEL's Controls collection, not within Page.Controls -->
</asp:Panel">
</form>
</body>
</html>

For this reason, you will be better served using Page.FindControl to look for controls.

Dim i as Integer
Dim lbDept as String
Dim lbOpn as String
Dim ctl As Control

For i=1 To 8

lbDept = String.Empty
ctl = Page.FindControl( "Dept" & i )
If Not ctl Is Nothing Then
Try
lbDept = CType( ctl, Textbox ).Text
Catch
End Try
If Not lbDept = String.Empty Then
' we found the value of a textbox with an ID of Deptx
' so, you can do your label assignments, or whatever
End If
End If

lbOpn = String.Empty
ctl = Page.FindControl( "Opn" & i )
If Not ctl Is Nothing Then
Try
lbOpn = CType( ctl, Textbox ).Text
Catch
End Try
If Not lbOpn = String.Empty Then
' we found the value of a textbox with an ID of Opnx
' so, you can do your label assignments, or whatever
End If
End If

Next

It's late at night here in Australia ... so I'm too tired to test this code.
I hope it helps you.
thanks! works perfect! i've still got a lot to learn. i'm trying to jump from vba to asp.net

0 comments:

Post a Comment