Reputation: 3065
Running VS 2013 VB.net.
I have 3 labels on my aspx page labelled label1, label2 and label3.
I want to loop through each one in the code behind and assign values to them.
Here is my code
Dim X As Integer = 1
For Each obj In values
Dim myLabel As Label
myLabel = TryCast(Me.FindControl("Label" + X), Label)
myLabel.Text = Math.Round(obj, 2)
X = X + 1
Next
I know there is only 3 obj's so x will always be between 1 and 3. What am I doing wrong as I get the following.
Conversion from string "Label" to type 'Double' is not valid
IF I change ("label" + x) to ("label1") I get
Object reference not set to an instance of an object.
on the line below.
Upvotes: 1
Views: 585
Reputation: 460228
You want to concatenate strings not to calculate, in VB.NET you use &
instead of +
(as opposed to C#). So this should work:
myLabel = TryCast(Me.FindControl("Label" & X), Label)
You should also set Option Strict
to On
, without exception. Then you first have to fix a lot of compiler errors, but it will help to write much more robust code. This wouldn't compile either:
myLabel.Text = Math.Round(obj, 2)
because a Math.Round
returns a Double
and Label.Text
is a String
. You just need to use Math.Round(obj, 2).ToString()
to fix it.
Here's a different approach to get your labels using Linq
:
Dim myLabels = From lbl In Me.Form.Controls.OfType(Of Label)()
Where lbl.ID.StartsWith("Label")
For Each lbl As Label In myLabels
' ... '
Next
Upvotes: 2
Reputation: 9024
Also since your using TryCast
check your variable before using it - it will be Nothing if it does not make the cast.
myLabel = TryCast(Me.FindControl("Label" & X.ToString), Label)
If myLabel IsNot Nothing Then
'safe to use variable here
End If
Upvotes: 0