[Resolved] [2008] Choose which label to write to
Hey, I have a form with 3 labels, a textbox and a button. I want to write a number in the textbox (1-3) and then press the button. Then, if the number in the textbox is 1, I want to write in label1 "TEST", if it's 2 I want to write in label2 etc. I know I can do it with a whole lot of if statements, but I think there has to be a way to do it simply.
I've tried this:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label(TextBox1.Text).text = "TEST"
End Sub
But it obviously didn't work...
Hope someone can help :D
Re: [2008] Choose which label to write to
vb Code:
me.controls("label" & TextBox1.Text).text = "TEST"
Re: [2008] Choose which label to write to
I would be more inclined to put the Labels in an array and then access the desired Label by index based on the value in the TextBox. That way you don't have to name your Labels identically with a numeric prefix.
vb.net Code:
Private labels As Label()
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As EventArgs) Handles MyBase.Load
Me.labels = New Label() {Me.Label1, _
Me.Label2, _
Me.Label3}
End Sub
Private Sub Button1_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles Button1.Click
Dim index As Integer
If Integer.TryParse(Me.TextBox1.Text, index) Then
index -= 1
If index >= 0 AndAlso index < Me.labels.Length Then
Me.labels(index).Text = "TEST"
End If
End If
End Sub
Re: [2008] Choose which label to write to
Quote:
Originally Posted by jmcilhinney
I would be more inclined to put the Labels in an array and then access the desired Label by index based on the value in the TextBox. That way you don't have to name your Labels identically with a numeric prefix.
isn't that a suffix?
regarding the labels, i'd agree with JMC for many labels, but i'd stick with what i posted for just 3 labels
Re: [2008] Choose which label to write to
Thanks both of you, they both worked well