• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 338
  • Last Modified:

Counting values of text in label

I have 4 labels that can contain numbers or blank results.  I need to calculate the total value of the text in the labels that are not blank and then divide by the number of labels that are not blank using a variable for the not blank labels. The result will then be placed in a 5th label.
 My code is attached to illustrate what I am trying to do.
dim variable as integer = 0
'code for iterating through the labels looking for the values that are not blank, adding them to a counter, storing the number of labels not "", then making that number "variable"
'the resulting equation
variable = variable + 1
lblall.Text = (Format((Val(label1.text) + Val(label2.text) + Val(label3.text) + Val(label4.text)) / variable, "0.0000"))

Open in new window

0
Blessed7777
Asked:
Blessed7777
1 Solution
 
guru_samiCommented:
Sample below. You might be able to loop if your lable ids will have some specific format...
but the login of calculation should remain same..
Dim numoflabels As Integer = 0
Dim sum As Decimal = 0
Dim average As Decimal = 0
If Not String.IsNullOrEmpty(Label1.Text) Then
    sum = (sum + Convert.ToDecimal(Label1.Text))
    numoflabels = (numoflabels + 1)
End If
If Not String.IsNullOrEmpty(Label2.Text) Then
    sum = (sum + Convert.ToDecimal(Label2.Text))
    numoflabels = (numoflabels + 1)
End If
If Not String.IsNullOrEmpty(Label3.Text) Then
    sum = (sum + Convert.ToDecimal(Label3.Text))
    numoflabels = (numoflabels + 1)
End If
If Not String.IsNullOrEmpty(Label4.Text) Then
    sum = (sum + Convert.ToDecimal(Label4.Text))
    numoflabels = (numoflabels + 1)
End If
If (numoflabels > 0) Then
    average = (sum / numoflabels)
End If
Label5.Text = average.ToString("N4")

Open in new window

0
 
Blessed7777Author Commented:
Thanks guru sami, you nailed it.
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now