简体   繁体   中英

Assign string value for decimal value

_item = new OutTYonetimOzet();

_item.Banka = Convert.ToDecimal(" "); 

liste.Add(_item);

There is a list called liste . In List item Banka named element is decimal value. I want to show the empty string when I show it on the screen. But this code is getting an error that can not be cast. What is the problem.

Error message is:

Input string was not in a correct format.

There's no such thing as a "blank decimal". decimal cannot have a value that is "blank" - it always has a numeric value. Convert.ToDecimal(" ") is nonsensical - there is nothing it can return that makes sense.

You could try using a Nullable<decimal> (aka decimal? ) perhaps; ie

public decimal? Banka {get;set;}

and

_item.Banka = null;

You can also use the decimal.TryParse instead of Convert . With this technique you can check if the string is valid.

        _item = new OutTYonetimOzet();

        decimal val = decimal.MinValue;

        if (decimal.TryParse(" ", out val))
        {
            _item.Banka = val;
        }
        else
        {
            //your default goes here
            _item.Banka = 0;
        }

        liste.Add(_item);

and as Mark suggested I would use Nullable<decimal> and use null as default value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM