Referencing Controld by String Name RRS feed

  • Question

  • I have a sample form with one button and 6 labels named Label1 - Label6.

    I'm experimenting in making a "Control Array" as we did in VB6.

    Code below works fine in and accomplishes what I want to achieve.

    Public Class Form1
        Dim Labels(6) As Label
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim i As Integer
            For i = 1 To 6
                Labels(i) = CType(Controls("label" & CStr(i)), Label)
                Labels(i).Text = MonthName(i, False)
        End Sub
    End Class

    I would like to use this same method in ASP.NET but am getting error.

    "Conversion from string "lblCYM1" to type 'Integer' is not valid."

    From command:

    MonthsY1(i) = CType(Controls(s), Label)

    Here's my ASP.Net Code

       Dim MonthsY1(12) As Label
                Dim i As Integer
                Dim s As String
                For i = 1 To 12
                    s = "lblCYM" & CStr(i)  'Labels lblCYM1 thru lblCYM12
                    MonthsY1(i) = CType(Controls(s), Label)
                    MonthsY1(i).Text = MonthName(i, False)

    Any suggestions as to how to make this work in ASP.NET?


    Friday, April 20, 2018 6:29 AM