开发者

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

开发者 https://www.devze.com 2023-01-28 00:23 出处:网络
With the following snippet Foo = IIf(String.IsNullOrEmpty(开发者_如何学JAVAtxtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim))

With the following snippet

Foo = IIf(String.IsNullOrEmpty(开发者_如何学JAVAtxtFoo.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))
0

精彩评论

暂无评论...
验证码 换一张
取 消