Adding ASP.Net Labels which contains value and Empty String using C#

RichardSa
 
on Dec 07, 2022 12:23 AM
472 Views

I have a label that adds the values of other labels and shows the total. But the error I am having is that if for example a label contains and empty value, I will have an error like input was not in the correct format.

How do I make it in such a way that even if a Label control contains a null or an empty value, it will still add up the values of other labels and show the total.

For example, label1 + label2 + label3 + label4 + label5 + label 6

Then if Label1 = 5

Label2 = 4

Label3 = "" (or empty and does not have any value)

Label4 = 10

Label5 = 1

Labe6 = "" (or empty and does not have any value)

Then LabelTotal = 20 (i.e., 5 + 4 + 10 + 1)

I have this code on my PageLoad event

lblTotal.Text = (int.Parse(Label1.Text) + int.Parse(Label2.Text) + int.Parse(Label3.Text) + int.Parse(Label4.Text) + int.Parse(Label5.Text) + int.Parse(Label6.Text)).ToString("###,##");
Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 07, 2022 04:42 AM
on Dec 08, 2022 11:41 PM

You need to check the Label value with string.IsNullOrEmpty. If its empty then set the value with 0.

Use this code.

lblTotal.Text = (
     int.Parse(!string.IsNullOrEmpty(Label1.Text) ? Label1.Text : "0")
   + int.Parse(!string.IsNullOrEmpty(Label2.Text) ? Label2.Text : "0")
   + int.Parse(!string.IsNullOrEmpty(Label3.Text) ? Label3.Text : "0")
   + int.Parse(!string.IsNullOrEmpty(Label4.Text) ? Label4.Text : "0")
   + int.Parse(!string.IsNullOrEmpty(Label5.Text) ? Label5.Text : "0")
   + int.Parse(!string.IsNullOrEmpty(Label6.Text) ? Label6.Text : "0")
 ).ToString("###,##");