简体   繁体   中英

VB.NET: Input string was not in a correct format

With the following snippet

Foo = IIf(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim))

I get the error when I submit the field without a value: "Input string was not in a correct format." I don't have any space or something else and String.IsNullOrEmpty(txtFoo.Text) returns true. What is wrong? Thank you.

IIF will evaluate:

Integer.Parse(txtFoo.Text.Trim) 

irrespective of whether:

String.IsNullOrEmpty(txtFoo.Text) 

is true or not (as it is just a function with three arguments passed to it, so all arguments must be valid). So even if txtFoo.text is empty , it's still trying to Parse it to an Integer in this case.

If you're using VS2008, you can use the IF operator instead which will short-circuit as you're expecting IIF to do.

IIf is a function call rather than a true conditional operator, and that means both arguments have to be evaluated. Thus, it just attempts to call Integer.Parse() if your string is Null/Nothing.

If you're using Visual Studio 2008 or later, it's only a one character difference to fix your problem:

Foo = If(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim())

This version of the If keyword is actually a true conditional operator that will do the short-circuit evaluation of arguments as expected.

If you're using Visual Studio 2005 or earlier, you fix it like this:

If String.IsNullOrEmpty(txtFoo.Text) Then Foo = 0 Else Foo = Integer.Parse(txtFoo.Text.Trim())

IIf is not a true ternary operator, it actually evaluates both parameter expressions. You probably want to use the If operator instead (VS 2008+).

You'd simply say

If(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim()))

One difference between the conditional and the "else" portion is the trimming of the string. You could try trimming the string before calling IsNullOrEmpty .

Foo = IIf(String.IsNullOrEmpty(txtFoo.Text.Trim), 0, Integer.Parse(txtFoo.Text.Trim))

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