2
_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.

2
  • Well want decimal value do you expect that to parse to? It sounds like you probably want to use Nullable<decimal> Commented Jan 25, 2018 at 7:52
  • 1
    Are you sure you can cast emptry string to decimal ? :o Commented Jan 25, 2018 at 7:52

2 Answers 2

7

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; i.e.

public decimal? Banka {get;set;}

and

_item.Banka = null;
Sign up to request clarification or add additional context in comments.

3 Comments

_item.Banka = Nullable<decimal>; is which is not valid in given comment.
You will need to change the implementation of _item so Banka is of type Nullable<decimal>
@Marc Exactly... in case it isn't obvious enough ;)
1

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.

3 Comments

This would be a correct solution for some random input string, not for a hardcoded space. And it would still show a 0 where a "blank" was wanted.
that's why I added the comment "your default goes here" and that nullable should be used. BTW I assumed that OP posted a minimal reproducible example so the blank is not hardcoded...
_item.Banka = Nullable<decimal>; is which is not valid in given comment. @Mat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.