Pergunta

I have 9 labels that are to contain 1 letter each from a text box called txthidden. And when i click on a button button3, the labels are meant to show up with the different array of letters. My problem isn't getting them to show up, it is that when there is not 9 letters in the textbox, it comes up with an error saying:

Index was outside the bounds of the array.

Is there a way to only show the labels that match the length of the text boxes length?

Thanks in advance!

Here is my code:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Dim hiddenarray() As Char
    hiddenarray = Me.txthidden.Text.ToCharArray
    lbl1.Text = hiddenarray(0)
    lbl2.Text = hiddenarray(1)
    lbl3.Text = hiddenarray(2)
    lbl4.Text = hiddenarray(3)
    lbl5.Text = hiddenarray(4)
    lbl6.Text = hiddenarray(5)
    lbl7.Text = hiddenarray(6)
    lbl8.Text = hiddenarray(7)
    lbl9.Text = hiddenarray(8)
End Sub
Foi útil?

Solução

There are many ways, for example a simple solution is to check:

lbl1.Text = IIf(hiddenarray.Lenght > 0, hiddenarray(0), "")
lbl2.Text = IIf(hiddenarray.Lenght > 1, hiddenarray(1), "")
'etc

Another way is to loop selecting the textbox dinamically by its name:

For i As Integer = 0 To hiddenarray.Lenght - 1
    Me.Controls("lbl" & i + 1).Text = hiddenarray(i)
Next
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top