Search code examples
asp.netloopswebformsfindcontrol

asp.net change format on various fields with same prefix, different suffix


I have the following VB code in an asp.net page.

It works fine, however I am sure there must be a better way (one only line perhaps) to cover all 6 fields within the block.

As you can see there are 4 rows of fields, each row contains 6 fields. Their ID all start with prefix "txtDO", then a number (7 to 11), then a suffix (_D, _C, _1, _2, _3, _B)

Note that these are not the only fields on the page, there are several groups. Since I have also additional code running within the VB loop, I need to keep it this way.

For l = 7 To 11                   
                CType(FindControl("txtDO" & l & "_D"), TextBox).Style.Add("border-bottom", "thin dotted #AD9F9F")
                CType(FindControl("txtDO" & l & "_C"), TextBox).Style.Add("border-bottom", "thin dotted #AD9F9F")
                CType(FindControl("txtDO" & l & "_1"), TextBox).Style.Add("border-bottom", "thin dotted #AD9F9F")
                CType(FindControl("txtDO" & l & "_2"), TextBox).Style.Add("border-bottom", "thin dotted #AD9F9F")
                CType(FindControl("txtDO" & l & "_3"), TextBox).Style.Add("border-bottom", "thin dotted #AD9F9F")
                CType(FindControl("txtDO" & l & "_B"), TextBox).Style.Add("border-bottom", "thin dotted #AD9F9F")
            Next l

I am looking for something like this, see the suffix * which covers ALL fields, therefore only one line of code instead of 6.

CType(FindControl("txtDO" & l & "*"), TextBox).Style.Add("border-bottom", "thin dotted #AD9F9F")

Is this possible ?


Solution

  • Why don't you use a nested Foreach loop...

    Dim letters() As String = {"_D", "_C", "_1", "_2", "_3", "_B"}
    For l = 7 To 11 
        For Each letter As String In letters                   
            CType(FindControl("txtDO" & l & letter).Style.Add("border-bottom", "thin dotted #AD9F9F")
        Next
    Next l