Search code examples
c#webformsteleriklabel

Label conversion returns error "input string was not in a correct format. "


I have some code like this:

decimal dBaseSal = decimal.Parse(dataBoundItemt.FindControl("lblTotalComp1") is Label ? (dataBoundItemt.FindControl("lblTotalComp1") as Label).Text : "0");

The label has the value of "". Because there is nothing in there at the moment. I am getting the error

input string was not in a correct format.

How can I do the validation like I am now with the Label, to make sure it is created in a label, but also, if it does come in as "", that the value is set to zero only on that condition. It needs to be a decimal format because sometimes there will be values that are decimals.

Thanks


Solution

  • Parse will return the value. Parse will throw an exception if the exact match was not found.

    TryParse will return boolean and out the value. TryParse will try to parse and convert, if there is not exact match found it will return false otherwise it will return true. The default of the type is returned if no exact match found.

    You can do something like this,

    decimal.TryParse(dataBoundItemt.FindControl("lblTotalComp1") is Label ? (dataBoundItemt.FindControl("lblTotalComp1") as Label).Text : "0", out decimal dBaseSal);