Finding and looping through labels - asp.net

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.

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

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

Related

ASP.NET determine number of digits after decimal point on GridView.RowDataBound

I am binding data to my GridView control and in one of the columns I have a price column which is of type double.
I also have a key in the web.config file that tells me how many digits to display after decimal point.
I want to display the data bound field according to that key in the web.config.
I saw this post on how to set the number of digists after decimal point: DataBinding Eval To 2 Decimal Place Doesn't Show 0
but I need a way of doing that with a variable that tells how many decimal places to use.
I tried this:
Private Sub grdData_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdData.RowDataBound
Dim numOfDigitsAfterDecimal = Integer.Parse(ConfigurationManager.AppSettings("numOfDigitsAfterDecimal"))
Dim d As String = ""
For Z As Integer = 0 To numOfDigitsAfterDecimal - 1
d = d + "#"
Next
e.Row.Cells(3).Text = String.Format("{0:0.{1}}", Double.Parse(e.Row.Cells(3).Text), d)
End Sub
but it does not work, however if I do:
e.Row.Cells(3).Text = String.Format("{0:0.##}", Double.Parse(e.Row.Cells(3).Text))
it does work and displays 2 decimal places.
you can use N0 or N1 or N2 and so the number will show the decimal place. check this article
Example :
number.ToString("N3")
// N: 1,054.32
// N0: 1,054
// N1: 1,054.3
// N2: 1,054.32
// N3: 1,054.322

Select number from a string classic asp

I need to get a 4/5 digit number which always comes directly after a #
For example it'll be "Item Title (#1234)" however it's not always in the same place or at the end.
Not sure how I go about doing that
You need to manually parse the string.
I've made a quick function for this:
'//return the number after delimeter string, if exists (first occurance only)
'//in case no number exists, returns Empty value
Function FindNumberAfter(rawValue, delimeterString)
Dim index, x, curChar
Dim sBuffer
FindNumberAfter = vbEmpty
index = InStr(rawValue, delimeterString)
If index>0 Then
For x=index+Len(delimeterString) To Len(rawValue)
curChar = Mid(rawValue, x, 1)
If IsNumeric(curChar) Then
sBuffer = sBuffer & curChar
Else
Exit For
End If
Next
If Len(sBuffer)>0 Then FindNumberAfter = CLng(sBuffer)
End If
End Function
Usage in your case:
Response.Write(FindNumberAfter("Item Title (#1234)", "#"))

Axis label values are generated dynamic, however require specific labels to be displayed

I am trying to dynamically generate axis label values as follows.
Dim dt As DataTable
dt = ds.Tables(0)
Dim y2max As Double = dt.Compute("max(return)", String.Empty) + 0.001
Dim y2min As Double = dt.Compute("min(return)", String.Empty) - 0.001
Dim ymax As Double = dt.Compute("max(TC_" & TC & ")", String.Empty) + 0.005
Dim ymin As Double = dt.Compute("min(TC_" & TC & ")", String.Empty) - 0.005
And generate the following chart.
http://i.imgur.com/LrfsvDT.png
I am able to achieve desired scaling with this approach , however i want by PRIMARY Y label values to have "1". Can i set an appropriate interval or format Y label values to achieve this.
This is what i wish to achieve
http://i.imgur.com/HKCrLmw.png
I am not concerned about the interval values/length, however i need my Blue line series to start with 1.
WRONG ANSWER: I think you are looking for the AxisY.IntervalOffset property. Why is it wrong? Because it shifts the labels. It just happened that it looked right in my previous attempt.
RIGHT ANSWER: If you set the AxisY.Crossing property to 1 then it will force it to use 1 as a label value, and calculate the other labels appropriately. You then need to set AxisY.IsStartedFromZero = False to avoid zero being included on the axis and AxisX.IsMarksNextToAxis = False to make the x-axis labels appear at the bottom edge of the chart.
So...
Sub GenerateChart()
Chart1.Legends.Clear()
Chart1.Series.Clear()
' generate some sample data
Dim s1 As New Series
For i = 0 To 180 Step 2
s1.Points.AddXY(i, Math.Sin(Math.PI * i / 60) * 0.004 + 1)
Next
Chart1.Series.Add(s1)
Chart1.Series(0).ChartType = SeriesChartType.Line
Chart1.Series(0).BorderWidth = 2
Chart1.ChartAreas(0).AxisY.IsStartedFromZero = False
Chart1.ChartAreas(0).AxisY.Crossing = 1
Chart1.ChartAreas(0).AxisX.IsMarksNextToAxis = False
' avoid the label "1.000" being formatted as "1"
Dim labelFormat = "0.000"
Chart1.ChartAreas(0).AxisY.LabelStyle = New LabelStyle With {.Format = labelFormat}
End Sub
Gives

chart datapoint operand usage

In the code snippet below I am attempting to compare two data points as I am trying to put all low value points in a pie chart dataset into on "Other" datapoint.
I am getting an "Cannot apply operator <> to operands of type System.....DataPoint and System.....DataPoint" on this code line " If pointValue <= minValue AndAlso Me.series.Points(index) <> colectedDataPoint "
Dim collectedValue As Double = 0.0
For index As Integer = 0 To Me.series.Points.Count - 1
Dim pointValue As Double = Math.Abs(Me.series.Points(index).YValues(0))
If pointValue <= minValue AndAlso Me.series.Points(index) <> colectedDataPoint Then
' Add point value to the collected value
collectedValue += pointValue
' Add point to supplemental series
Me.supplementalSeries.Points.Add(Me.series.Points(index).Clone())
' Remove point from the series
Me.series.Points.RemoveAt(index)
index -= 1
End If
Next
but yet if I write the same loop in C# that equivalent line is fine;
this.series.Points[index] != colectedDataPoint
anyone have a solution since the whole project is written in vb.net and i'd prefer to keep it uniform.

ASP.NET Reverse Loop

I have some code and I'm trying to do my For loop in reverse and it doesn't seem to work
Session("mysession") = "1234-5678-"
Dim delimiters As Char() = New Char() {"-"C}
Dim mystring As String() = Trim(Session("mysession")).Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
For x = 0 to mystring.Length - 1
'Do Something
Next
That works but shows it in the wrong order I'm trying to reverse it by simply doing this
For mystring.Length - 1 to x = 0
But I'm getting an error
Expression is a value and therefore cannot be the target of an assignment.
Any ideas?
Thanks
The syntax of your reversed loop is incorrect. It should be:
For x = mystring.Length - 1 To 0 Step -1

Resources