samedi 30 décembre 2017

Visual Basic: reference label control from variable derived from checkbox control

I'm writing a simple Windows Form app in VB using VS Community 2017.

I have 64 checkboxes with 64 associated labels, named chk1 / lbl1 up to chk64 / lbl64. When a checkbox is checked, I want to extract a character from a string and show the answer in the label: e.g. if chk12 is checked, I want lbl12 to be enabled and the text to display the 12th character of the string.

To save writing 64 separate handlers I'm trying to do it in one. I can extract the checked number (e.g. 12) OK and write it to a string, but when I try to manipulate the label control I get an 'Object reference not set to an instance of an object' error.

The code I've come up with so far (largely from searching in here) is:

Private Sub CheckedChanged(sender As Object, e As EventArgs) _
  Handles chk1.CheckedChanged, chk2.CheckedChanged 'etc. to 64

    ' wanted behaviour
    'If chk1.Checked Then
    '    lbl1.Enabled = True
    '    lbl1.Text = GetChar(userString, 1)
    'End If
    'If chk2Checked Then
    '    lbl2.Enabled = True
    '    lbl2.Text = GetChar(userString, 2)
    'End If
    ' etc. (to 64)

    Dim resultsLabel As String
    Dim userCheckedBox As Integer

    userCheckedBox = CInt(DirectCast(sender, CheckBox).Text)
    resultsLabel = "lbl" & DirectCast(sender, CheckBox).Text

    Me.Controls(resultsLabel).Enabled = True
    Me.Controls(resultsLabel).Text = GetChar(userString, userCheckedBox)

End Sub

I'd be very grateful if someone can nudge me over the line with this. Many thanks!




Aucun commentaire:

Enregistrer un commentaire