简体   繁体   English

VB.NET:输入字符串的格式不正确

[英]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. 我没有任何空间或其他东西,并且String.IsNullOrEmpty(txtFoo.Text)返回true。 What is wrong? 怎么了? Thank you. 谢谢。

IIF will evaluate: IIF将评估:

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. 因此,即使txtFoo.text is empty ,在这种情况下,它仍会尝试将其解析为Integer。

If you're using VS2008, you can use the IF operator instead which will short-circuit as you're expecting IIF to do. 如果使用的是VS2008,则可以改用IF运算符,因为它会导致IIF短路。

IIf is a function call rather than a true conditional operator, and that means both arguments have to be evaluated. IIf是函数调用,而不是真正的条件运算符,这意味着必须对两个参数都进行求值。 Thus, it just attempts to call Integer.Parse() if your string is Null/Nothing. 因此,如果您的字符串为Null / Nothing,它只会尝试调用Integer.Parse()。

If you're using Visual Studio 2008 or later, it's only a one character difference to fix your problem: 如果您使用的是Visual Studio 2008或更高版本,则只能解决一个字符差异:

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关键字实际上是一个真正的条件运算符,它将按预期对参数进行短路评估。

If you're using Visual Studio 2005 or earlier, you fix it like this: 如果您使用的是Visual Studio 2005或更早版本,请按以下步骤修复它:

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. IIf不是真正的三元运算符,它实际上计算两个参数表达式。 You probably want to use the If operator instead (VS 2008+). 您可能想改为使用If运算符(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 . 您可以在调用IsNullOrEmpty之前尝试修剪字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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