yemi oladejo
yemi oladejo

Reputation: 85

Sum of multiple labels to print on separate labels

I have 7 labels, of which print out the value of the calculations

 private void label29_Click(object sender, EventArgs e)
        {
            double a1 = (1.0 / trackBar1.Value);







            label29.Text = (1.0 / trackBar1.Value).ToString();



        }

that is for one label i am now trying to have the answers for all 7 labels summed onto one label. The problem i think i have is that they are all string values but even if i removes the .ToString method i still get an error on the 8th label which has all the sums of the 7 labels

double label56 = label29 + label30 + label31 + label32 + label33 + label34 + label35;

Upvotes: 0

Views: 615

Answers (1)

user586399
user586399

Reputation:

You need to get text of each label. However, Text is of type string, which is not a number that can be summed (Actually it is summed in a different manner, just concatenating the strings near to each other).

So we convert each text to a double so when can sum:

double result = double.Parse(label29.Text) + double.Parse(label30.Text)  
      + double.Parse(label31.Text) + double.Parse(label32.Text) 
      + double.Parse(label33.Text) + double.Parse(label34.Text) 
      + double.Parse(label35.Text);
label56.Text = result.ToString(); //convert back to string for display

Better approach is to put your labels in an array, and loop over it to find sum:

Label[] arr = new Label[]{ label29 , label30 , label31 , label32 , label33 , label34 , label35 };
double result = 0;
foreach (var item in arr)
   result += double.Parse(item.Text);
label56.Text = result.ToString(); //convert back to string for display

Upvotes: 1

Related Questions