0

I have a VB.Net Sub that loads values from a list into textboxes on a form (this form is where the sub is located). If I reference a text box directly, say txt01.Text = "Blah", it works just fine; but if I reference the same text box programmatically, like Me.Controls("txt01").Text = "Blah", I keep getting System.NullReferenceException.

Here's the code:

Private Sub lboxCodebooks_SelectedIndexChanged(sender As Object, e As 
EventArgs) Handles lboxCodebooks.SelectedIndexChanged

    'On Error GoTo ErrorHandler

    If lboxCodebooks.SelectedIndex < 0 Then GoTo CleanUpAndExit

    grpCodebook.Enabled = True

    Dim c As Codebook = CB.Item(lboxCodebooks.SelectedIndex)
    Dim ctlName As String
    Dim ctl As Control

    txtCodebookName.Text = c.Name

    For i As Integer = 1 To 93

        ctlName = "txt" & Format(i, "00")

        ctl = Me.Controls(ctlName) ' This sets ctl to Nothing - but why?

        ctl.Text = Mid(c.AlphaCodex, i, 1) ' NullReference error here.

    Next

CleanUpAndExit:
    On Error Resume Next

    c = Nothing

    Exit Sub

ErrorHandler:
    Call ErrorHandler(Err)
    Resume CleanUpAndExit

End Sub

What on earth am I doing wrong here?

Ňɏssa Pøngjǣrdenlarp
  • 37,255
  • 11
  • 50
  • 147
David Mancini
  • 198
  • 2
  • 17

0 Answers0