Home > Enterprise >  How to convert Label.Text into Numbers
How to convert Label.Text into Numbers

Time:10-17

if (Application["Summary12"] != null)
        {
            string Name = Application["Summary12"].ToString();
            lbl12Cost.Text = Name;
        }
if (Application["Summary12Pro"] != null)
        {
            string Name = Application["Summary12Pro"].ToString();
            lblProCost.Text = Name;
        }

I want to convert both of these Labels "lbl12Cost" & "lblProCost" into integers that I can add up. Currently, both of them are Label.Text, but I want to convert them into numbers.

For example, if lbl12Cost = 1 & lblProCost = 2, I want to add them up as numbers so it will be equals to 3. But in this case, both of them are text and the output will be 1 2 because it's text instead of numbers.

I have tried using int.tryparse and convert.toint32 but It won't work. Was wondering if there is any way to convert text to numbers?

I am currently using ASP.NET, HTML WebForm, aspx.cs file.

CodePudding user response:

I hope this is what you are asking.

int x = Convert.ToInt32(lbl1.Text)   Convert.ToInt32(lbl2.Text);

or if you are accessing value in javaScript then use parseInt() function as below:

int x = parseInt("string value 1")   parseInt("string value 2");

CodePudding user response:

If you are sure that label's texts are convertible to an integer then you can directly do the below.

int sum = Convert.ToInt32(lbl12Cost.Text)   Convert.ToInt32(lblProCost.Text); 

But you said you are getting the below exception, which means the text is not convertible to an integer value. So in this case you should use int.TryParse method. which returns true if the input string is convertible to int otherwise it returns false. so if it returns false you can handle it as your requirement. I have given one example below.

Input string was not in a correct format

int cost = 0;
if(int.TryParse(lbl12Cost.Text, out cost) == true)
{
    ...
}
else
{
    ...
}

CodePudding user response:

You can use int.TryParse:

if (int.TryParse(lbl12Cost.Text, out int a) && 
    int.TryParse(lblProCost.Text, out int b)) {
  // Both lbl12Cost.Text and lblProCost.Text contain valid int values a and b

  // we can add these integer values, e.g. 
  int sum = a   b;

  lblSomeOtherLabel.Text = $"total: {sum}";
} 
else {
  // At least lbl12Cost.Text or lblProCost.Text doesn't have valid int 
}

CodePudding user response:

First check if there is a value for the label.

var num1 = Convert.ToInt32( lbl12Cost.Text);
  •  Tags:  
  • c#
  • Related