开发者

im having syntax issues pulling data from 6 text boxes with identical names (other than a number at the end) in a for loop

I have 6 different text boxes with similar names:

txtBox1, txtBox2....txtBox6

I also have an array:

dim intValue (0 to 5) as Integer

Now I want to use a for loop to assign the value in each text box to a corresponding space in the array, concatenating the value of the loop counter with the string "txtBox" and retrieving the data using the .text method.

here is my code:

 For count As Integer = 0 To 5
            Dim strCount As String = count开发者_开发知识库
            Dim strTxtBox As String = "txtBox" & strCount
            intValues(count) = Convert.toInt32(strTxtBox.Text)
        Next 

the issue is that the string name doesn't point to txtBox1, txtBox 2 etc.

Thanks in advance for the help.


If you want to access the control name, you have to use the property "Name".

You should try something like that:

    For i As Integer = 0 To 5
        For Each c As Control In Controls
            If c.Name = "txtBox" & i Then
                intValue(i) = Convert.ToInt32(c.Text)
            End If
        Next
    Next i

The above code is just an example, but it should work for you. Anyway you can write a better code checking the type of the control or maybe using a different loop logic, but the basic idea is that if you want to use in your code the name od the control you have to use the NAME property.


strTxtBox is a string, nothing more. You cannot refer to control names by String without special code. Rather than go down that path, I'd create an array and populate it with text boxes:

Dim txtBoxes As TextBox() = {txtBox1, txtBox2, txtBox3, txtBox4, txtBox5, txtBox6}
Dim intValues As Integer(0 To 5)
For count As Integer = 0 To 5
    intValues(count) = Convert.ToInt32(txtBoxes(count).Text)
Next


The easiest way is to iterate through the contents of Controls to find the textboxes. You can either:

  • Use the .Tag property to label textboxes to identify them, or as the other answer points out, use the .Name property.

  • If you have a lot of other controls on the form, and they may not be in order, you could also check each control to see if it's a textbox. Assume they are in reverse order, as the Controls array goes from end to beginning.

    Dim nums() As Integer = {10, 20, 30, 40, 50, 60}
    Dim ctrl As Control
    For Each ctrl In Me.Controls
        If TypeOf (ctrl) Is TextBox Then
            ctrl.Text = nums(Val(ctrl.Name(ctrl.Name.Length - 1)) - 1)
        End If
    Next 
    

You could also instantiate an array of textboxes programmatically, but you'd have to set all of the placement, etc. by hand.

As I commented on the answer below, you may need to cast the ctrl to a System.Web.UI.Control to access the .Name, using DirectCast.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜